main()。Socket = IP + Port。雙方各綁一個 Socket,建立連接通道。
accept() 阻塞等待連接。ServerSocket ss = new ServerSocket(6666);
while (true) {
Socket s = ss.accept(); // 阻塞
DataInputStream dis = new DataInputStream(s.getInputStream());
String msg = dis.readUTF(); // 阻塞讀取
System.out.println(msg);
}
Socket s = new Socket("127.0.0.1", 6666);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
Thread.sleep(30000); // 模擬延遲
dos.writeUTF("Hello Server!");
accept()/read() 阻塞導致單線程無法併發 → 需多線程/線程池/NIO。DatagramSocket/DatagramPacket,無連接狀態。掌握 TCP/UDP 差異、Socket 模型、阻塞 I/O 特性,是進階 Netty、NIO、微服務通信的基石。