您好,登錄后才能下訂單哦!
本文實例為大家分享了java實現TCP聊天程序的具體代碼,供大家參考,具體內容如下
服務端代碼:
package com.test.server; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) { new Server().startServer(); } public void startServer(){ try { //服務器在9990端口監聽客戶端的連接 ServerSocket ss = new ServerSocket(9999); System.out.println("server is listening..."); while(true){ //阻塞的accept方法,當一個客戶端連接上,才會返回Socket對象 Socket s = ss.accept(); System.out.println("a client has connected!"); //開啟線程處理通信 new CommunicateThread(s).start(); } } catch (IOException e) { e.printStackTrace(); } } public class CommunicateThread extends Thread{ Socket socket; DataInputStream dis; DataOutputStream dos; public CommunicateThread(Socket socket){ this.socket = socket; try { dis = new DataInputStream(socket.getInputStream()); dos = new DataOutputStream(socket.getOutputStream()); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { super.run(); //讀取客戶端發過來的消息 String msg = null; try { while((msg = dis.readUTF()) != null){ System.out.println("client send msg :" + msg); String replyMsg = "server reply : " + msg; dos.writeUTF(replyMsg); System.out.println("server reply msg :" + replyMsg); } } catch (IOException e) { e.printStackTrace(); } } } }
客戶端代碼:
package com.test.client; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.util.Scanner; public class Client { public static void main(String[] args) { new Client().startClient(); } public void startClient(){ try { //連接到服務器 Socket socket = new Socket("localhost", 9999); DataInputStream dis = new DataInputStream(socket.getInputStream()); DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); Scanner scanner = new Scanner(System.in); String line = null; listenServerReply(dis); while((line = scanner.nextLine()) != null){//讀取從鍵盤輸入的一行 dos.writeUTF(line);//發給服務端 System.out.println("client send msg : " + line); } } catch (Exception e) { e.printStackTrace(); } } //監聽服務端回復的消息 public void listenServerReply(final DataInputStream dis){ new Thread(){ @Override public void run() { super.run(); String line = null; try { while((line = dis.readUTF()) != null){ System.out.println("client receive msg from server: " + line); } } catch (IOException e) { e.printStackTrace(); } } }.start(); } }
先啟動服務端,再啟動客戶端,在客戶端的控制臺輸入消息并回車,就可以發送消息給客戶端了,客戶端收到消息后,馬上會回復一個消息
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。