基于TCP套接字的Echo服务器
//N o w J a v a . c o m import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; public class Main { public static void main(String[] args) { try { ServerSocket serverSocket = new ServerSocket(12900, 100, InetAddress.getByName("localhost")); System.out.println("Server started at: " + serverSocket); while (true) { System.out.println("Waiting for a connection..."); Socket activeSocket = serverSocket.accept(); System.out.println("Received a connection from " + activeSocket); Runnable runnable = () -> handleClientRequest(activeSocket); new Thread(runnable).start();//n o w j a v a . c o m - 时 代 Java } } catch (IOException e) { e.printStackTrace(); } } public static void handleClientRequest(Socket socket) { BufferedReader socketReader = null; BufferedWriter socketWriter = null; try { socketReader = new BufferedReader(new InputStreamReader( socket.getInputStream())); socketWriter = new BufferedWriter(new OutputStreamWriter( socket.getOutputStream())); String inMsg = null; while ((inMsg = socketReader.readLine()) != null) { System.out.println("Received from client: " + inMsg); String outMsg = inMsg;