完整示範基於 ServerSocket/Socket 的雙向文字通訊系統。Client 使用 Swing GUI,Server 以單執行緒迴圈回應(可擴充為多執行緒)。代碼分層:ClientAgent/ServerAgent 封裝通訊細節,UI 僅負責事件觸發與顯示。
+----------------+ TCP 1001 +----------------+ | Swing Client | <----------------> | ServerAgent | | (JavaClient) | PrintStream/ | (main loop) | | | DataInputStream | | +----------------+ +----------------+
public class ClientAgent {
private PrintStream out;
private DataInputStream in;
public ClientAgent(String host, int port) throws IOException {
Socket socket = new Socket(host, port);
out = new PrintStream(socket.getOutputStream(), true); // autoFlush
in = new DataInputStream(socket.getInputStream());
}
public void sendRequest(String req) { out.println(req); }
public String getResponse() throws IOException { return in.readLine(); }
public void close() {
try { in.close(); } catch (Exception ignore) {}
try { out.close(); } catch (Exception ignore) {}
}
}
public class JavaClient extends JFrame implements ActionListener {
private JTextField inputField;
private JTextArea outputArea;
private ClientAgent agent;
public JavaClient() {
// GUI 初始化略
sendButton.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == sendButton) {
String req = inputField.getText();
agent.sendRequest(req);
try {
outputArea.append("\nServer: " + agent.getResponse());
} catch (IOException ex) {
outputArea.append("\n[通訊錯誤]");
}
}
}
public static void main(String[] args) throws IOException {
JavaClient frame = new JavaClient();
frame.setVisible(true);
frame.agent = new ClientAgent("127.0.0.1", 1001);
}
}
public class ServerAgent {
private ServerSocket serverSocket;
private Socket clientSocket;
private DataInputStream in;
private PrintStream out;
public ServerAgent(int port) throws IOException {
serverSocket = new ServerSocket(port);
System.out.println("Server 監聽 port " + port);
clientSocket = serverSocket.accept();
in = new DataInputStream(clientSocket.getInputStream());
out = new PrintStream(clientSocket.getOutputStream(), true);
out.println("歡迎連線!");
}
public String getRequest() throws IOException { return in.readLine(); }
public void sendResponse(String resp) { out.println(resp); }
public static void main(String[] args) throws IOException {
ServerAgent sa = new ServerAgent(1001);
while (true) {
String req = sa.getRequest();
if (req == null) break; // Client 斷線
sa.sendResponse("Echo: " + req); // 簡單回應邏輯
}
}
}
ExecutorService,每個 Client 分配一執行緒(new Thread(() -> handle(clientSocket)).start())。