欢迎来到天天文库
浏览记录
ID:43403330
大小:115.50 KB
页数:12页
时间:2019-09-30
《java聊天室部分主要代码》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、ChatClient.javaimportjava.awt.*;importjava.io.*;importjava.net.*;importjava.applet.*;importjava.util.Hashtable;publicclassChatClientextendsAppletimplementsRunnable{Socketsocket=null;DataInputStreamin=null;//读取服务器端发来的消息DataOutputStreamout=null;//向服务器端发送的消息InputInfo用户名提交界面=null;UserChat聊天界面
2、=null;HashtablelistTable;//用于存放在线用户的用户名的散列表Label提示条;Panelnorth,center;Threadthread;publicvoidinit(){setSize(1000,800);intwidth=getSize().width;intheight=getSize().height;listTable=newHashtable();setLayout(newBorderLayout());用户名提交界面=newInputInfo(listTable);inth=用户名提交界面.getSize().height;聊天界
3、面=newUserChat("",listTable,width,height-(h+5));聊天界面.setVisible(false);提示条=newLabel("正在连接到服务器...",Label.CENTER);提示条.setForeground(Color.red);north=newPanel(newFlowLayout(FlowLayout.LEFT));center=newPanel();north.add(用户名提交界面);north.add(提示条);center.add(聊天界面);add(north,BorderLayout.NORTH);add
4、(center,BorderLayout.CENTER);validate();}publicvoidstart(){if(socket!=null&&in!=null&&out!=null){try{socket.close();in.close();out.close();聊天界面.setVisible(false);}catch(Exceptionee){}}//客户端与服务器端简历连接try{socket=newSocket(this.getCodeBase().getHost(),6666);in=newDataInputStream(socket.getInp
5、utStream());out=newDataOutputStream(socket.getOutputStream());}catch(IOExceptionee){提示条.setText("连接失败");}//客户端成功连接服务器端if(socket!=null){InetAddressaddress=socket.getInetAddress();提示条.setText("连接:"+address+"成功");用户名提交界面.setSocketConnection(socket,in,out);north.validate();}if(thread==null){t
6、hread=newThread(this);thread.start();}}publicvoidstop(){try{socket.close();thread=null;}catch(IOExceptione){this.showStatus(e.toString());}}publicvoidrun(){while(thread!=null){if(用户名提交界面.getchatornot()==true){聊天界面.setVisible(true);聊天界面.setName(用户名提交界面.getName());聊天界面.setSocketConnection(s
7、ocket,in,out);提示条.setText("祝聊天快乐!");center.validate();break;}try{Thread.sleep(100);}catch(Exceptione){}}}}ChatMain.javaimportjava.io.*;importjava.net.*;importjava.util.*;publicclassChatMain{publicstaticvoidmain(Stringargs[]){ServerSocketserver=null;Socketyou=null;Ha
此文档下载收益归作者所有