重慶分公司,新征程啟航
為企業(yè)提供網(wǎng)站建設(shè)、域名注冊(cè)、服務(wù)器等服務(wù)
為企業(yè)提供網(wǎng)站建設(shè)、域名注冊(cè)、服務(wù)器等服務(wù)
小編給大家分享一下java如何實(shí)現(xiàn)在線聊天室,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
在線聊天室
服務(wù)器:
public class Chat { public static void main(String[]args) throws IOException { System.out.println("服務(wù)器啟動(dòng)中..."); //創(chuàng)建服務(wù)器 ServerSocket server=new ServerSocket(9999); //阻塞式等待連接,當(dāng)客戶端Socket創(chuàng)建好以后才開(kāi)啟 while(true) { Socket client=server.accept(); System.out.println("一個(gè)客戶端建立了連接"); new Thread(()->{ DataInputStream dis = null; DataOutputStream dos = null; try { dis = new DataInputStream(client.getInputStream()); dos = new DataOutputStream(client.getOutputStream()); } catch (IOException e1) { e1.printStackTrace(); } boolean flag=true; while(flag) { String msg = null; try { msg = dis.readUTF(); dos.writeUTF(msg); dos.flush(); } catch (IOException e) { //當(dāng)斷掉客戶端連接時(shí),不用循環(huán)再讀取數(shù)據(jù) flag=false; } //返回消息 } try { if(null!=dos) { dos.close(); } } catch (IOException e) { e.printStackTrace(); } try { if(null!=dis) { dis.close(); } } catch (IOException e) { e.printStackTrace(); } try { if(null!=client) { client.close(); } } catch (IOException e) { e.printStackTrace(); } }).start(); } } }
客戶端:
public class Client {
public static void main(String[]args) throws UnknownHostException, IOException { System.out.println("客戶端啟動(dòng)中..."); Socket client=new Socket("localhost",9999); //客戶端發(fā)送消息 BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); DataOutputStream dos=new DataOutputStream(client.getOutputStream()); DataInputStream dis =new DataInputStream(client.getInputStream()); boolean flag=true; while(flag) { System.out.println("請(qǐng)輸入消息"); String msg=br.readLine(); dos.writeUTF(msg); dos.flush(); //獲取消息 msg=dis.readUTF(); System.out.println(msg); } dos.close(); dis.close(); client.close(); } }
以上是“java如何實(shí)現(xiàn)在線聊天室”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)網(wǎng)站制作公司行業(yè)資訊頻道!
創(chuàng)新互聯(lián)www.cdcxhl.cn,專業(yè)提供香港、美國(guó)云服務(wù)器,動(dòng)態(tài)BGP最優(yōu)骨干路由自動(dòng)選擇,持續(xù)穩(wěn)定高效的網(wǎng)絡(luò)助力業(yè)務(wù)部署。公司持有工信部辦法的idc、isp許可證, 機(jī)房獨(dú)有T級(jí)流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確進(jìn)行流量調(diào)度,確保服務(wù)器高可用性。佳節(jié)活動(dòng)現(xiàn)已開(kāi)啟,新人活動(dòng)云服務(wù)器買多久送多久。