客戶端: import java.io.IOException; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ChatClient { public static void main(String[] args) { //使用線程池 ExecutorService service=Executors.newFixedThreadPool(3); try { Socket socket=new Socket("127.0.0.1", 8888); service.execute(new SendTread(socket)); service.execute(new ReveicerThread(socket)); //new SendTread(socket).start(); } catch (IOException e) { e.printStackTrace(); } } } 服務端: import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ChatServer { public static void main(String[] args) { //使用線程池 ExecutorService service=Executors.newFixedThreadPool(3); ServerSocket serverSocket; try { serverSocket = new ServerSocket(8888); Socket socket=serverSocket.accept(); service.execute(new SendTread(socket)); service.execute(new ReveicerThread(socket)); } catch (IOException e) { e.printStackTrace(); } } } 客戶端線程: import java.io.IOException; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; /* * 一個客戶端與一個服務端進行聊天。 * 1:接收數據, * 2:發送數據。 * 同時進行。:線程。 一個線程負責接收數據,一個線程負責發送數據。 */ public class SendTread extends Thread { Scanner sc = new Scanner(System.in); String str = null; // 定義構造方法獲取套接 private Socket socket; public SendTread(Socket socket) { this.socket = socket; } @Override public void run() { // 得到輸出管道。 OutputStream os = null; try { os = socket.getOutputStream(); while (true) { System.out.println("請輸入發送的數據"); str = sc.nextLine(); if("".equals(str)||str==null||"886".equals(str)){ break; } os.write(str.getBytes()); os.write("\r\n".getBytes()); //若是接收端是用bufferReader來讀的話要加上回車換行符 } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { os.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } 服務端線程: import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.Socket; import java.util.Scanner; public class ReveicerThread extends Thread{ Scanner sc=new Scanner(System.in); String str=null; private Socket socket; public ReveicerThread(Socket socket) { this.socket = socket; } public void run() { InputStream is=null; BufferedReader br=null; try { is=socket.getInputStream(); br=new BufferedReader(new InputStreamReader(is)); String ip=socket.getInetAddress().getHostAddress(); int port=socket.getPort(); //若是是用bufferReader來讀的話,發送端要加上回車換行符 while(true){ str=br.readLine(); if(str==null||socket==null||"".equals(str)){break;} System.out.println("ip "+ip+" : 端口"+port+str); } } catch (IOException e) { e.printStackTrace(); } try { is.close(); br.close(); } catch (IOException e) { e.printStackTrace(); } } }