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

Java TCP 網路程式設計入門:雙向通訊與關閉流程完整範例

     編輯:Java 綜合教學

Java TCP 網路程式設計入門:雙向通訊與關閉流程完整範例

本文提供兩個完整的 TCP 通訊練習:基礎單向傳輸、進階雙向回饋,展示 Socket/ServerSocket、輸入輸出流、shutdownOutput() 正確關閉流程。

練習一:客戶端發送、服務端接收列印

// 客戶端
@Test
public void client() {
    Socket socket = null;
    OutputStream os = null;
    try {
        socket = new Socket(InetAddress.getByName("192.168.1.101"), 9090);
        os = socket.getOutputStream();
        os.write("我是客戶端".getBytes());
    } catch (IOException e) { e.printStackTrace(); }
    finally { close(os, socket); }
}

// 服務端
@Test
public void server() {
    ServerSocket ss = null;
    Socket s = null;
    InputStream is = null;
    try {
        ss = new ServerSocket(9090);
        s = ss.accept(); // 阻塞等待連線
        is = s.getInputStream();
        byte[] buf = new byte[20];
        int len;
        while ((len = is.read(buf)) != -1) {
            System.out.println(new String(buf, 0, len));
        }
        System.out.println("收到來自 " + s.getInetAddress().getHostName() + " 的連線");
    } catch (IOException e) { e.printStackTrace(); }
    finally { close(is, s, ss); }
}

練習二:雙向通訊(服務端回覆「已收到請求」)

關鍵點:客戶端呼叫 socket.shutdownOutput() 明確告知服務端「發送完畢」,否則服務端 read() 會持續阻塞等待更多資料,導致雙向通訊死鎖。

// 客戶端
@Test
public void client() {
    Socket s = null;
    OutputStream os = null;
    InputStream is = null;
    try {
        s = new Socket(InetAddress.getByName("192.168.1.101"), 9797);
        os = s.getOutputStream();
        os.write("我是客戶端".getBytes());
        
        // 關鍵:通知服務端輸出結束
        s.shutdownOutput();
        
        // 接收服務端回覆
        is = s.getInputStream();
        byte[] buf = new byte[20];
        int len;
        while ((len = is.read(buf)) != -1) {
            System.out.println(new String(buf, 0, len));
        }
    } catch (IOException e) { e.printStackTrace(); }
    finally { close(is, os, s); }
}

// 服務端
@Test
public void server() {
    ServerSocket ss = null;
    Socket s = null;
    InputStream is = null;
    OutputStream os = null;
    try {
        ss = new ServerSocket(9797);
        s = ss.accept();
        is = s.getInputStream();
        
        // 讀取客戶端訊息
        byte[] buf = new byte[20];
        int len;
        while ((len = is.read(buf)) != -1) {
            System.out.println(new String(buf, 0, len));
        }
        
        // 回覆客戶端
        os = s.getOutputStream();
        os.write("已收到請求".getBytes());
    } catch (IOException e) { e.printStackTrace(); }
    finally { close(os, is, s, ss); }
}

關鍵最佳實踐總結

  1. 流關閉順序:先關閉流,再關閉 Socket,最後關閉 ServerSocket
  2. shutdownOutput():雙向通訊必須,告知對方「不再發送資料」,讓對方 read() 返回 -1
  3. 緩衝區大小:byte[20] 僅為示範,實際建議 byte[1024] 或 BufferedInputStream
  4. 執行緒安全:真實伺服器需為每個客戶端開啟獨立執行緒處理
  5. IP 綁定:new ServerSocket(port) 綁定所有網卡,new ServerSocket(port, backlog, InetAddress.getByName("127.0.0.1")) 僅本機

作者註:這是第一篇部落格記錄,TCP 基礎但關鍵細節(shutdownOutput、流關閉順序)最容易踩坑,特別標註備查。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved