Created
May 28, 2020 08:59
-
-
Save kojilin/cd46d60e38575fe477b2d1f5f9b59203 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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