java通信二:利用Socket实现聊天室功能
生活随笔
收集整理的這篇文章主要介紹了
java通信二:利用Socket实现聊天室功能
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
最近研究了下java socket通信基礎(chǔ),利用代碼實現(xiàn)了一個簡單的多人聊天室功能,現(xiàn)把代碼共享下,希望能幫到有興趣了解的人。
目錄結(jié)構(gòu):
ChatClient:
package com.panda.chat;import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*;@SuppressWarnings("serial") public class ChatClient extends Frame {private TextArea ta = new TextArea();private TextField tf = new TextField();private DataOutputStream dos = null;private DataInputStream dis = null;private Socket socket = null;private boolean bConnected = false;private Thread thread=null;public static void main(String[] args) {new ChatClient().frameClient();}public void frameClient(){setSize(400, 400);setLocation(400,300);add(ta,BorderLayout.NORTH);add(tf,BorderLayout.SOUTH);pack();tf.addActionListener(new TfListener());//關(guān)閉窗口事件監(jiān)聽this.addWindowListener(new WindowAdapter() {@Overridepublic void windowClosing(WindowEvent e) {disconnected();System.exit(0);}});this.connect();setVisible(true);}//鏈接服務(wù)器地址private void connect(){try {socket = new Socket("127.0.0.1", 8888);thread=new Thread(new ChatThread());thread.start();dos = new DataOutputStream(socket.getOutputStream());dis = new DataInputStream(socket.getInputStream());} catch (UnknownHostException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}//斷開連接private void disconnected(){bConnected = false;try {dos.close();dis.close();socket.close();} catch (IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}}//鍵盤回車事件private class TfListener implements ActionListener{@Overridepublic void actionPerformed(ActionEvent e) {String strMsg = tf.getText();tf.setText("");try {dos.writeUTF(strMsg);dos.flush();} catch (IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}}}//開啟線程接受服務(wù)器信息private class ChatThread implements Runnable{@Overridepublic void run() {try {bConnected = true;while(bConnected){String msg = dis.readUTF();String taText = ta.getText();ta.setText(taText+msg+"\n");}} catch (SocketException e) {System.out.println("退出");;} catch (IOException e) {e.printStackTrace();}}} }
ChatServer:
package com.panda.chat;import java.io.*; import java.net.*; import java.util.*;public class ChatServer {private boolean started = false;private List<ChatThread> chatThreads = new ArrayList<ChatThread>();public static void main(String[] args) {new ChatServer().startServer();}private void startServer(){try {//開啟服務(wù)端SocketServerSocket seso = new ServerSocket(8888);started = true;while(started){//接受客戶端連接請求Socket sos = seso.accept();System.out.println("一個客戶端已連接");//開啟線程處理客戶端通信ChatThread ct = new ChatThread(sos);chatThreads.add(ct);new Thread(ct).start();}} catch (IOException e) {e.printStackTrace();} }private class ChatThread implements Runnable{private Socket socket;private DataInputStream din=null;private DataOutputStream don=null;private boolean bConnected = false;public ChatThread(Socket socket) {super();this.socket = socket;}//發(fā)送信息的函數(shù)private void send(String strMsgIn){try{don.writeUTF(strMsgIn);don.flush();}catch(IOException e){e.printStackTrace();}}@Overridepublic void run() {try{din = new DataInputStream(socket.getInputStream());don = new DataOutputStream(socket.getOutputStream());//讀取數(shù)據(jù)bConnected = true;while(bConnected){String strMsgIn = din.readUTF();System.out.println(strMsgIn);//接收到數(shù)據(jù)后發(fā)送給每個客戶端for(int i =0;i<chatThreads.size();i++){chatThreads.get(i).send(strMsgIn);}}}catch (IOException e) {try {//如果客戶端出錯或關(guān)閉,直接關(guān)閉連接,并移除List中的當(dāng)前線程socket.close();chatThreads.remove(this);} catch (IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}} finally{try {din.close();don.close();socket.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}} } 運行ChatSever后,再同時打開多次ChatClient,就可以實現(xiàn)多人聊天了,你也試試。
總結(jié)
以上是生活随笔為你收集整理的java通信二:利用Socket实现聊天室功能的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何让AI让3000位艺术家画同一张画
- 下一篇: office2021下载|office2