Skip to content

Instantly share code, notes, and snippets.

@kojilin
Created May 28, 2020 08:59
Show Gist options
  • Select an option

  • Save kojilin/cd46d60e38575fe477b2d1f5f9b59203 to your computer and use it in GitHub Desktop.

Select an option

Save kojilin/cd46d60e38575fe477b2d1f5f9b59203 to your computer and use it in GitHub Desktop.
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.channels.ServerSocketChannel;
public class BlockingServer {
public static void main(String[] args) throws IOException {
run();
}
static void run() throws IOException {
final ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
final ServerSocket socket = serverSocketChannel.socket();
final InetSocketAddress inetSocketAddress = new InetSocketAddress(5556);
socket.setReuseAddress(true);
socket.bind(inetSocketAddress);
while (true) {
final Socket client = socket.accept();
// each connection use 1 thread.
new Thread(() -> {
try (client) {
byte[] buf = new byte[1024];
System.out.println(">>>client.isClosed():" + client.isClosed());
while (!client.isClosed()) {
final int read = client.getInputStream().read(buf);
if (read > 0) {
client.getOutputStream().write(buf, 0, read);
} else {
client.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Closed connection.");
}).start();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment