欢迎来到天天文库
浏览记录
ID:38197784
大小:160.04 KB
页数:9页
时间:2019-06-07
《java_课程设计_聊天窗口》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、JAVA课程设计----------聊天窗口姓名:学号:班级:计科2老师:赵宏宇设计了一个简单的聊天室程序,用于实现聊天室的基本功能,分为了客户端和服务器端,服务器端可以接收多个连接,客户端可以连接服务器。客户端发送消息给服务器端,服务器接收消息,转发给所有的客户。一、源程序代码服务器端源代码,ServerTest.javaimportjava.io.BufferedInputStream;importjava.io.BufferedOutputStream;importjava.io.DataIn
2、put;importjava.io.DataInputStream;importjava.io.DataOutputStream;importjava.io.IOException;importjava.net.ServerSocket;importjava.net.Socket;importjava.util.Enumeration;importjava.util.Vector;importcom.sun.corba.se.spi.activation.ServerHeldDown;publicc
3、lassServerTest{publicServerTest(intport)throwsIOException{ServerSocketserver=newServerSocket(port);while(true){Socketconn=server.accept();DataInputStreaminputStream=newDataInputStream(conn.getInputStream());Stringwho=inputStream.readUTF();System.out.pr
4、int("Clinet"+"(IP"+conn.getInetAddress()+")"+who+"enter!"+"");ServerHandercn=newServerHander(who,conn);cn.start();}}publicstaticvoidmain(String[]args)throwsIOException{newServerTest(9001);//TODOAuto-generatedmethodstub}}classServerHanderextendsThread
5、{Socketsocket;DataInputStreamin;DataOutputStreamout;Stringwho;protectedstaticVectorclientlist=newVector();publicServerHander(Stringname,Socketsocket)throwsIOException{this.who=name;this.socket=socket;in=newDataInputStream(ne
6、wBufferedInputStream(socket.getInputStream()));out=newDataOutputStream(newBufferedOutputStream(socket.getOutputStream()));}publicvoidrun(){try{clientlist.addElement(this);sendallclient("欢迎"+who+"进入聊天室");while(true){Stringmsg=in.readUTF();sendallclient(
7、who+"说:"+msg);}}catch(IOExceptione){System.out.println("Clientexitorerror.");}clientlist.removeElement(this);sendallclient(who+"退出!");try{socket.close();}catch(IOExceptionex){System.out.println("Connectionhasbeenclosed");}}protectedstaticvoidsendallcli
8、ent(Stringmsg){synchronized(clientlist){Enumerationallclients=clientlist.elements();while(allclients.hasMoreElements()){ServerHanderserh=(ServerHander)allclients.nextElement();try{serh.out.writeUTF(msg);serh.out.flush();}c
此文档下载收益归作者所有