欢迎来到天天文库
浏览记录
ID:6051368
大小:42.50 KB
页数:6页
时间:2018-01-01
《聊天系统(客户端、服务器端) java版 完整代码》由会员上传分享,免费在线阅读,更多相关内容在应用文档-天天文库。
1、客户端:importjava.awt.*;importjava.awt.event.*;importjava.io.*;importjava.net.*;publicclassChatClientextendsFrame{Sockets=null;DataOutputStreamdos=null;DataInputStreamdis=null;privatebooleanbConnected=false;TextFieldtfTxt=newTextField();TextAreataContent=newTextArea();ThreadtRecv=newThread
2、(newRecvThread());publicstaticvoidmain(String[]args){newChatClient().launchFrame();}publicvoidlaunchFrame(){setLocation(400,300);this.setSize(300,300);add(tfTxt,BorderLayout.SOUTH);add(taContent,BorderLayout.NORTH);pack();this.addWindowListener(newWindowAdapter(){@Overridepublicvoidwind
3、owClosing(WindowEventarg0){disconnect();System.exit(0);}});tfTxt.addActionListener(newTFListener());setVisible(true);connect();tRecv.start();}publicvoidconnect(){try{s=newSocket("127.0.0.1",8888);dos=newDataOutputStream(s.getOutputStream());dis=newDataInputStream(s.getInputStream());Sys
4、tem.out.println("connected!");bConnected=true;}catch(UnknownHostExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();}}publicvoiddisconnect(){try{dos.close();dis.close();s.close();}catch(IOExceptione){e.printStackTrace();}/*try{bConnected=false;tRecv.join();}catch(In
5、terruptedExceptione){e.printStackTrace();}finally{try{dos.close();dis.close();s.close();}catch(IOExceptione){e.printStackTrace();}}*/}privateclassTFListenerimplementsActionListener{publicvoidactionPerformed(ActionEvente){Stringstr=tfTxt.getText().trim();//taContent.setText(str);tfTxt.se
6、tText("");try{//System.out.println(s);dos.writeUTF(str);dos.flush();//dos.close();}catch(IOExceptione1){e1.printStackTrace();}}}privateclassRecvThreadimplementsRunnable{publicvoidrun(){try{while(bConnected){Stringstr=dis.readUTF();//System.out.println(str);taContent.setText(taContent.ge
7、tText()+str+'');}}catch(SocketExceptione){System.out.println("退出了,bye!");}catch(EOFExceptione){System.out.println("推出了,bye-bye!");}catch(IOExceptione){e.printStackTrace();}}}}服务器端importjava.io.*;importjava.net.*;importjava.util.*;publicclassChatServer{booleanstarted=false;Ser
此文档下载收益归作者所有