import java.util.*; import java.net.*; import java.io.*; public class Server { public static void main(String[] args) { for (String portStr : args) { try { int port = Integer.parseInt(portStr); new Thread(new ServerTask(port)).start(); } catch (NumberFormatException e) { System.out.println("Incorrect port: " + portStr); } } } private static class ServerTask implements Runnable { private int port; public ServerTask(int port) { this.port = port; } public void run() { try (ServerSocket serverSocket = new ServerSocket(port)) { while (true) { Socket clientSocket = serverSocket.accept(); new Thread(new ClientHandler(clientSocket)).start(); } } catch (IOException e) { System.out.println("Error starting the server on port " + port); } } } private static class ClientHandler implements Runnable { private Socket clientSocket; public ClientHandler(Socket clientSocket) { this.clientSocket = clientSocket; } public void run() { try (InputStream input = clientSocket.getInputStream()) { byte[] buffer = new byte[20]; int bytesRead = input.read(buffer); String receiveData = new String(buffer, 0, bytesRead); System.out.println(receiveData); } catch (IOException e) { System.out.println("Error receiving data from client"); e.printStackTrace(); } finally { try { clientSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter