Java 應用環境本質上是瀏覽器/服務器模型,即 Web 三層架構,區別於傳統二層 C/S 架構。本文剖析 Java 網絡應用模型、核心類庫與 Socket 通訊實戰代碼。
傳統 C/S 通過消息傳遞直連資料庫。Web 模型將服務端拆分為:
客戶端瀏覽器僅負責展示與交互,業務邏輯前移至應用服務器,實現「瘦客戶端、厚服務端」。
Java 針對分布式計算提供豐富網絡 API:
java.net(基礎/TCP/UDP)、java.net.ftp、java.net.www.http、java.net.www.html、java.net.www.content。運算分散策略:服務端負責查詢計算,客戶端負責渲染展示,提升整體吞吐與動態擴展能力。
典型流程:
ServerSocket 監聽端口。Socket 發起連接。accept() 返回新 Socket,派生線程處理通訊。accept(),每連接創建 Connection 線程處理 I/O,主線程繼續監聽。DataInputStream/PrintStream 包裝 Socket 原始流,便捷處理文本行讀寫。public class Server extends Thread {
public static final int DEFAULT_PORT = 6543;
private ServerSocket listenSocket;
public Server(int port) throws IOException {
this.listenSocket = new ServerSocket(port == 0 ? DEFAULT_PORT : port);
start();
}
@Override
public void run() {
try {
while (true) {
Socket client = listenSocket.accept();
new Connection(client); // 隱含 start()
}
} catch (IOException e) { /* 日誌記錄 */ }
}
static class Connection extends Thread {
private final Socket client;
private final DataInputStream in;
private final PrintStream out;
Connection(Socket socket) throws IOException {
this.client = socket;
this.in = new DataInputStream(client.getInputStream());
this.out = new PrintStream(client.getOutputStream());
start();
}
@Override
public void run() {
try {
String line;
while ((line = in.readLine()) != null) {
// 業務邏輯:反轉字符串返回
out.println(new StringBuilder(line).reverse());
}
} catch (IOException ignored) {
} finally {
try { client.close(); } catch (IOException ignored) {}
}
}
}
public static void main(String[] args) {
new Server(args.length > 0 ? Integer.parseInt(args[0]) : 0);
}
}
public class Client {
public static final int DEFAULT_PORT = 6543;
public static void main(String[] args) throws IOException {
String host = args[0];
int port = args.length > 1 ? Integer.parseInt(args[1]) : DEFAULT_PORT;
try (Socket socket = new Socket(host, port);
DataInputStream in = new DataInputStream(socket.getInputStream());
PrintStream out = new PrintStream(socket.getOutputStream());
BufferedReader console = new BufferedReader(new InputStreamReader(System.in))) {
System.out.println("Connected to " + socket.getInetAddress() + ":" + socket.getPort());
String line;
while ((line = console.readLine()) != null) {
out.println(line);
String response = in.readLine();
if (response == null) break;
System.out.println(response);
}
}
}
}
上述為基礎 Socket 編程教學模型。生產環境建議採用: