導語://創建一個滾動面板,將文本域作為其顯示組件JScrollPaneshowPanel=newJScrollPane(chatContent);chatContent.setEditable(false);//設置文本域不可編輯JPanelinputPanel=newJPanel();//創建一個JPanel面板inputField=newJTextField(20);//創建一個文本框sendBt=newJButton("發送");//創建一個發送按鈕//為按鈕添加事件這篇文章主要為大家詳細介紹了java聊天室的實現代碼,一個多客戶端聊天室,支持多客戶端聊天,具有一定的參考價值,感興趣的小伙伴們可以參考一下sendBt.addActionListener(newActionListener(){//為按鈕添加一個監聽事件publicvoidactionPerformed(ActionEvente){//重寫actionPerformed方法Stringcontent=inputField.getText();//獲取輸入的文本信息//判斷輸入的信息是否為空if(content!=null&&!content.trim().equals("")){//如果不為空,將輸入的文本追加到到聊天窗口chatContent.append("本人:"+content+"\n");}else{//如果為空,提示聊天信息不能為空chatContent.append("聊天信息不能為空"+"\n");}inputField.setText("");//將輸入的文本域內容置為空try{ Clientclient=null; while(true){ socket=ss.accept(); System.out.println("客戶駕到"); client=newClient(socket); clients.add(client); newThread(client).start(); }}catch(IOExceptione){ e.printStackTrace();}}privateclassClientimplementsRunnable{privateSocketsocket=null;InputStreamin=null;DataInputStreamdin=null;OutputStreamout=null;DataOutputStreamdos=null;booleanflag=true;publicClient(Socketsocket){ this.socket=socket; try{ in=socket.getInputStream(); din=newDataInputStream(in); }catch(IOExceptione){ System.out.println("接受消息失敗"); e.printStackTrace(); }}publicvoidrun(){ Stringmessage; try{ while(flag){ message=din.readUTF(); //System.out.println("客戶說:"+message); forwordToAllClients(message); } }catch(SocketExceptione){ flag=false; System.out.println("客戶下線"); clients.remove(this); //e.printStackTrace(); }catch(EOFExceptione){ flag=false; System.out.println("客戶下線"); clients.remove(this); //e.printStackTrace(); }catch(IOExceptione){ flag=false; System.out.println("接受消息失敗"); clients.remove(this); e.printStackTrace(); } if(din!=null){ try{ din.close(); }catch(IOExceptione){ System.out.println("din關閉失敗"); e.printStackTrace(); } } if(in!=null){ try{ in.close(); }catch(IOExceptione){ System.out.println("din關閉失敗"); e.printStackTrace(); } } if(socket!=null){ try{ socket.close(); }catch(IOExceptione){ System.out.println("din關閉失敗"); e.printStackTrace(); } }}/** *功能:轉發給所有客戶端
2022-04-25閱讀量:1280
*客****
趙*鐳19994****14
*客****
黎*嬋13189****17
*客****
澹*宇17327****95
郭*婷18260****02
*客****
曹*瑩13301****52
*金15153****76
院校動態
院校分類