您好,登錄后才能下訂單哦!
本文實例為大家分享了Java Socket聊天室功能的具體代碼,供大家參考,具體內容如下
Client.java
import java.io.*; import java.net.*; import java.util.*; public class Client { public int port = 8083; Socket socket = null; public static void main(String[] args) { new Client(); //開始執行 } public Client() { try { socket = new Socket("127.0.0.1", port); new Cthread().start(); BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); String msg1; while ((msg1 = br.readLine()) != null) { System.out.println(msg1); } } catch (Exception e) { } } class Cthread extends Thread { public void run() { try { BufferedReader re = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(socket.getOutputStream(), true); String msg2; while (true) { msg2 = re.readLine(); pw.println(msg2); } } catch (Exception e) { e.printStackTrace(); } } } }
Server.java
import java.net.*; import java.io.*; import java.util.*; public class Server { int port; List<Socket> clients; ServerSocket server; public Server() { try { port = 8083; clients = new ArrayList<Socket>(); server = new ServerSocket(port); System.out.println("服務器已啟動"); int co=1; while (true) { Socket socket = server.accept(); clients.add(socket); Mythread mythread = new Mythread(socket,co); co++; mythread.start(); } } catch (Exception ex) { System.out.println("vv"); } } public static void main(String[] args) { new Server(); } class Mythread extends Thread { Socket ssocket; private int count; private BufferedReader br; private PrintWriter pw; public String msg; public Mythread(Socket s,int c) { ssocket = s; count=c; } public void run() { try { br = new BufferedReader(new InputStreamReader(ssocket.getInputStream())); msg = "歡迎【" +"Client "+count + "】進入聊天室!當前聊天室有【" + clients.size() + "】人"; sendMsg(); while ((msg = br.readLine()) != null) { msg = "【" +"Client "+count + "】說:" + msg; sendMsg(); } } catch (Exception ex) { } } public void sendMsg() { try { System.out.println(msg); for (int i = clients.size() - 1; i >= 0; i--) { pw = new PrintWriter(clients.get(i).getOutputStream(), true); pw.println(msg); pw.flush(); } } catch (Exception ex) { } } } }
運行結果:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。