Socket 為雙向位元組串流端點,擁有 IP 位址與埠號。通訊雙方需自行約定資料格式化與解析規則,雖較繁瑣但靈活度最高、應用範圍最廣。

核心流程:Server 監聽埠口 → Client 發起連線 → 雙向串流資料交換 → 關閉連線。
java.net.Socket:客戶端通訊端點java.net.ServerSocket:伺服端監聽端點new Socket(host, port) 建立連線(含三向交握)getInputStream() / getOutputStream()import java.io.*;
import java.net.*;
public class SocketCommunicationClient {
public static void main(String[] args) {
try {
Socket clientSocket = new Socket("mice", 9000);
OutputStream output = clientSocket.getOutputStream();
DataInputStream input = new DataInputStream(clientSocket.getInputStream());
int c;
String response;
while ((c = System.in.read()) != -1) {
output.write((byte) c);
if (c == '\n') { // 換行觸發發送
output.flush();
response = input.readLine(); // 阻塞等待回應
System.out.println("Communication: " + response);
}
}
output.close(); input.close(); clientSocket.close();
} catch (Exception e) {
System.err.println("Exception: " + e);
}
}
}
程式從標準輸入讀取字元,累積至換行後發送至伺服器,阻塞等待回應並列印,循環至輸入結束。
new ServerSocket(port) 建立監聽 Socketaccept() 阻塞等待客戶連線,回傳新 Socket 實例ServerSocket 結束服務採用多執行緒可實現並發伺服器,持續監聽新連線。
import java.net.*;
import java.io.*;
public class SocketCommunicationServer {
public static void main(String[] args) {
try {
boolean flag = true;
ServerSocket serverSocket = new ServerSocket(9000);
System.out.println("伺服器在埠 9000 監聽中...");
while (flag) {
Socket client = serverSocket.accept(); // 阻塞等待連線
DataInputStream input = new DataInputStream(
new BufferedInputStream(client.getInputStream()));
PrintStream output = new PrintStream(
new BufferedOutputStream(client.getOutputStream()));
String inputLine;
while ((inputLine = input.readLine()) != null) {
if (inputLine.equals("Stop")) { flag = false; break; }
output.println(inputLine); // 回應客戶端
output.flush();
}
output.close(); input.close(); client.close();
}
serverSocket.close();
} catch (IOException e) { /* 處理異常 */ }
}
}
伺服器接收訊息並原樣回應,收到 "Stop" 關閉服務。實務上可擴充為執行緒池處理高併發。
accept() 回傳的新 Socket 專屬於該連線,主 ServerSocket 繼續監聽