首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java Socket 通訊實戰:Swing Client + 多執行緒 Server 架構

     編輯:Java 相關知識

完整示範基於 ServerSocket/Socket 的雙向文字通訊系統。Client 使用 Swing GUI,Server 以單執行緒迴圈回應(可擴充為多執行緒)。代碼分層:ClientAgent/ServerAgent 封裝通訊細節,UI 僅負責事件觸發與顯示。

架構圖

+----------------+      TCP 1001      +----------------+
|  Swing Client  | <----------------> |  ServerAgent   |
|  (JavaClient)  |  PrintStream/      |  (main loop)   |
|                |  DataInputStream   |                |
+----------------+                    +----------------+

ClientAgent 通訊類

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) {}
    }
}

Swing Client 主程式

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);
    }
}

ServerAgent 端

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); // 簡單回應邏輯
        }
    }
}

改進方向

  • Server 引入 ExecutorService,每個 Client 分配一執行緒(new Thread(() -> handle(clientSocket)).start())。
  • 協議升級:定義 JSON/Protobuf 訊息格式,支援指令分發(登入、查詢、推播)。
  • 加入心跳檢測、SSL 加密、優雅關閉(ShutdownHook)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved