java 網路程式設計中 TCP 實現聊天
阿新 • • 發佈:2021-09-05
編寫程式碼
1,新建服務端 TcpServerDemo01
package com.xiang.lesson02; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; //服務端 public class TcpServerDemo01 { public static void main(String[] args) { ServerSocket socket = null; Socket accept = null; InputStream inputStream = null; ByteArrayOutputStream byteArrayOutputStream = null; // 1,需要有一個地址 // new 一個地址; try { socket = new ServerSocket(999); while (true){ // 2, 等待客戶端連線 accept = socket.accept(); // 3, 讀取 客戶端的訊息 inputStream = accept.getInputStream(); // 管道流 byteArrayOutputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len = inputStream.read(buffer)) != -1) { byteArrayOutputStream.write(buffer, 0, len); } System.out.println(byteArrayOutputStream.toString()); } } catch (IOException e) { e.printStackTrace(); } finally { //關閉資源 if (byteArrayOutputStream != null) { try { byteArrayOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (accept != null) { try { accept.close(); } catch (IOException e) { e.printStackTrace(); } } if (socket != null) { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
2,新建服務端 TcpClientDemo01
package com.xiang.lesson02; import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.nio.charset.StandardCharsets; //客戶端 public class TcpClientDemo01 { public static void main(String[] args) { Socket socket = null; OutputStream outputStream = null; // 1,要知道伺服器的地址 // 連這個地址 localhost 999 try { InetAddress serverIP = InetAddress.getByName("127.0.0.1"); // 2 埠號 int port = 999; // 3,建立一個 socket 連線 socket = new Socket(serverIP, port); // 4,傳送訊息 io 流 // 輸出 流 outputStream = socket.getOutputStream(); // 寫 outputStream.write("你好,歡迎學習到了網路程式設計".getBytes(StandardCharsets.UTF_8)); } catch (Exception e) { e.printStackTrace(); } finally { if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (socket != null) { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } }