导语://创建一个滚动面板,将文本域作为其显示组件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阅读量:1581
*清19924****21
钟*月18172****01
*客****
*客****
*客****
巴*克13779****77
*华15852****30
张*豪17596****25
*客****
*客****
院校动态
院校分类