public class ServerSocketTest { public static void main(String[] args) { try { ServerSocket serverSocket = new ServerSocket(9999); ExecutorService executorService = Executors.newFixedThreadPool(10); while (true) { final Socket socket = serverSocket.accept(); Thread thread = new Thread(new Runnable() { @Override public void run() { try { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); String str; while ((str = bufferedReader.readLine()) != null) { System.out.println(str); } } catch (IOException e) { e.printStackTrace(); } } }); executorService.execute(thread); } } catch (IOException e) { e.printStackTrace(); } } }
public class ClientSocketTest { public static void main(String[] args) { try { Socket socket = new Socket("localhost", 9999); BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8")); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in, "UTF-8")); String str; while ((str = bufferedReader.readLine()) != null) { bufferedWriter.write(str); bufferedWriter.write("\n"); bufferedWriter.flush(); } } catch (IOException e) { e.printStackTrace(); } } }
原文地址:https://www.cnblogs.com/zfzf1/p/11661930.html
时间: 2024-10-11 08:33:30