Java中利用Tcp/ip连接多人交互聊天室的实现
作者
Java中利用Tcp/ip连接多人交互聊天室的实现,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
使用指南:
1.运行Server.java文件,保证服务端的开启 2.运行UI.java文件,界面登陆。每运行一个UI文件并登陆进去,就代表一个客户进了群聊中,可进行对话。
程序简单易懂,非常适合初学者练习网络编程的知识。
Client.java
importjava.net.*; importjava.io.*; importjava.util.*; publicclassClient{ Stringname; Sockets; UIui; //构造方法,把UI对象传过来 publicClient(UIui){ this.ui=ui; } //从登陆界面获得名字并传去服务端 publicvoidgetName(Stringname){ try{ s=newSocket("127.0.0.1",3000); Cli1d=newCli1(s,ui); d.start(); this.name=name; DataOutputStreamdos=newDataOutputStream(s.getOutputStream()); dos.writeUTF(name); }catch(Exceptione){ e.printStackTrace(); } } //从聊天界面获得要发送的内容并经服务器转发给各个客户端 publicvoidsay(Stringcontent){ try{ DataOutputStreamdos=newDataOutputStream(s.getOutputStream()); dos.writeUTF(content); }catch(Exceptione){ e.printStackTrace(); } } } //输入和输出 classCli1extendsThread{ UIui; Sockets; publicCli1(Sockets,UIui){ this.s=s; this.ui=ui; } publicvoidrun(){ try{ while(true){ DataInputStreamdis=newDataInputStream(s.getInputStream()); Stringcontent=dis.readUTF(); if(!content.equals("")&&content!=null){ System.out.println(content); ui.say(content); } } }catch(Exceptione){ e.printStackTrace(); } } }
Server.java
importjava.net.*; importjava.io.*; importjava.util.*; publicclassServer{ staticSockets; staticSocket[]soc; staticString[]name; staticintk=5,i=0,j; publicstaticvoidmain(String[]args){ Serverser=newServer(); try{ ServerSocketss=newServerSocket(3000); soc=newSocket[k]; name=newString[k]; while(true){ s=ss.accept(); soc[i]=s; j=i; i++; DataOutputStreamdos=newDataOutputStream(s.getOutputStream()); DataInputStreamdis=newDataInputStream(s.getInputStream()); name[j]=dis.readUTF(); System.out.println(name[j]+"已进入群聊!"); dos.writeUTF("欢迎你,"+name[j]); newSer1().start(); } }catch(ConnectExceptione){ System.out.println("连接异常!!"); }catch(IOExceptione){ e.printStackTrace(); } } } classSer1extendsThread{ publicintj; publicvoidrun(){ try{ DataInputStreamread=newDataInputStream((Server.soc[Server.j]).getInputStream()); j=Server.j; while(true){ Stringcon=read.readUTF(); if(con!=null){ System.out.println("该线程j为"+j); for(inti=0;i<Server.soc.length;i++){ if((i!=j)&&(Server.soc[i]!=null)){ DataOutputStreamdos=newDataOutputStream((Server.soc[i]).getOutputStream()); dos.writeUTF(Server.name[Server.j]+"发送于"+(newDate())); dos.writeUTF(con); } } }else{break;} } }catch(Exceptione){ e.printStackTrace(); } } }
UI.java
importjava.awt.*; importjavax.swing.*; importjava.awt.event.*; publicclassUI{ //主方法 publicstaticvoidmain(String[]args){ UIui=newUI(); ui.cli=newClient(ui); ui.initFrame(); ui.showLogin(); } Ser1ser1=newSer1(); //初始化业务对象 publicClientcli=null; publicvoidinitCli(){ } //初始化主窗口 publicintwidth=720; publicintheight=550; publicJFramejFrame=null;//界面窗口 publicJLayeredPanelayeredPane=null;//层叠容器 publicJPanelbackLayer=null;//背景层 publicJPanelfrontLayer=null;//前景层 publicCardLayoutcardLayout=null;//前景层布局器 publicvoidinitFrame(){ jFrame=newJFrame("老友聚乐部"); layeredPane=newJLayeredPane(); layeredPane.setPreferredSize(newDimension(width,height)); jFrame.add(layeredPane); jFrame.setResizable(false); jFrame.pack(); jFrame.setVisible(true); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); backLayer=newJPanel(); ((FlowLayout)backLayer.getLayout()).setHgap(0); ((FlowLayout)backLayer.getLayout()).setVgap(0); backLayer.setSize(width,height); backLayer.setLocation(0,0); JLabelbg=newJLabel(newImageIcon("12.jpg")); backLayer.add(bg); layeredPane.add(backLayer,newInteger(0)); frontLayer=newJPanel(); cardLayout=newCardLayout(0,0); frontLayer.setLayout(cardLayout); frontLayer.setOpaque(false); frontLayer.setSize(width,height); frontLayer.setLocation(0,0); layeredPane.add(frontLayer,newInteger(1)); } //登录界面 publicJPanelloginPane=null; publicJTextFieldloginCodeInput=null; publicJLabelloginTipsLabel=null; publicvoidshowLogin(){ if(loginPane==null){ loginPane=newJPanel(); loginPane.setOpaque(false); BoxloginBox=Box.createVerticalBox(); loginBox.add(Box.createVerticalStrut(180)); JPanelwelcome_panel=newJPanel(); welcome_panel.setOpaque(false); JLabelwelcome_label=newJLabel("老友俱乐部"); welcome_label.setForeground(Color.WHITE); welcome_label.setFont(newFont("微软雅黑",Font.PLAIN,30)); welcome_panel.add(welcome_label); loginBox.add(welcome_panel); loginBox.add(Box.createVerticalStrut(50)); JPanelcode_panel=newJPanel(); code_panel.setOpaque(false); JLabelcode_label=newJLabel("姓名:"); code_label.setForeground(Color.WHITE); code_label.setFont(newFont("微软雅黑",Font.PLAIN,25)); code_panel.add(code_label); loginCodeInput=newJTextField(10); loginCodeInput.setFont(newFont("微软雅黑",Font.PLAIN,25)); code_panel.add(loginCodeInput); loginBox.add(code_panel); loginBox.add(Box.createVerticalStrut(30)); JPanelbtn_panel=newJPanel(); btn_panel.setOpaque(false); JButtonlogin_btn=newJButton("登录"); login_btn.setFont(newFont("微软雅黑",Font.PLAIN,15)); btn_panel.add(login_btn); JButtonreset_btn=newJButton("重置"); reset_btn.setFont(newFont("微软雅黑",Font.PLAIN,15)); btn_panel.add(reset_btn); loginBox.add(btn_panel); loginBox.add(Box.createVerticalStrut(10)); JPaneltips_panel=newJPanel(); tips_panel.setOpaque(false); loginTipsLabel=newJLabel(""); loginTipsLabel.setForeground(newColor(238,32,32)); loginTipsLabel.setFont(newFont("微软雅黑",Font.PLAIN,20)); tips_panel.add(loginTipsLabel); loginBox.add(tips_panel); loginPane.add(loginBox); frontLayer.add("loginPane",loginPane); cardLayout.show(frontLayer,"loginPane"); frontLayer.validate(); loginCodeInput.requestFocus(); reset_btn.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEventae){ loginCodeInput.setText(""); loginTipsLabel.setText(""); loginCodeInput.requestFocus(); } }); login_btn.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEventae){ Stringcode_str=loginCodeInput.getText(); if("".equals(code_str)){ loginTipsLabel.setText("姓名不能为空!"); loginCodeInput.requestFocus(); }else{ cli.getName(code_str); showTalk(); } } }); }else{ cardLayout.show(frontLayer,"loginPane"); loginCodeInput.setText(""); loginTipsLabel.setText(""); loginCodeInput.requestFocus(); } } //聊天主界面 publicJPanelmenuPane=null; publicJTextAreainput=null; publicJTextAreatalk=newJTextArea(25,70); publicvoidshowTalk(){ menuPane=newJPanel(); menuPane.setOpaque(false); menuPane.setLayout(newBorderLayout()); JPanelup=newJPanel(); BoxtipsBox=Box.createVerticalBox(); menuPane.add(up,BorderLayout.NORTH);//北边顶上 up.add(tipsBox); JLabeltips_label=newJLabel("在线朋友"); tips_label.setForeground(Color.WHITE); tips_label.setFont(newFont("微软雅黑",Font.PLAIN,20)); tips_label.setAlignmentX(Component.LEFT_ALIGNMENT); tipsBox.add(tips_label); tipsBox.add(Box.createVerticalStrut(10)); JLabelupTxt=newJLabel("");//接收在线朋友(需完善) tipsBox.add(upTxt); JPaneltalk_panel=newJPanel();//中间聊天对话框 talk_panel.setOpaque(false); menuPane.add(talk_panel,BorderLayout.WEST); JScrollPanesp=newJScrollPane(talk); talk_panel.add(talk); BoxinputBox=Box.createHorizontalBox();//下边输入框 menuPane.add(inputBox,BorderLayout.SOUTH); JPanelinput_panel=newJPanel(); input_panel.setOpaque(false);//放置输入框 input=newJTextArea(4,30); input.setFont(newFont("微软雅黑",Font.PLAIN,20)); input.setAlignmentX(Component.LEFT_ALIGNMENT); input_panel.add(input); inputBox.add(input_panel); inputBox.add(Box.createHorizontalStrut(0)); JButtonsend_btn=newJButton("发送"); send_btn.setFont(newFont("微软雅黑",Font.PLAIN,15)); inputBox.add(send_btn); frontLayer.add("menuPane",menuPane); cardLayout.show(frontLayer,"menuPane"); frontLayer.validate(); send_btn.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEventae){ Stringappend=talk.getText(); Stringcontent=input.getText(); talk.setText(append+'\n'+content); input.setText(""); cli.say(content); } }); } publicvoidsay(Stringcontent){ if(talk!=null){ Stringappend=talk.getText(); talk.setText(append+'\n'+content); } } }
关于Java中利用Tcp/ip连接多人交互聊天室的实现问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注恰卡编程网行业资讯频道了解更多相关知识。
目录
推荐阅读
0 条评论
本站已关闭游客评论,请登录或者注册后再评论吧~