您好,欢迎访问三七文档
当前位置:首页 > 商业/管理/HR > 广告经营 > Java-Socket聊天室完整源代码
1/5以下代码实现的功能:在一个局域网内,两人在Eclipse的控制台上,可以点对点的进行聊天,并且某一方可以同时输入多句话,以下时实例图片:Server端的示意图:Client端的示意图:说明:本人不才,Java初学者,自己平时也喜欢总结一些东西,然后与大家分享,同时希望得到Java高手的指正和指导,更希望能和广大的Java爱好者交朋友,共同学习Java,分享经验,一起进步。本人QQ:1134135987,非Java爱好者勿加,谢谢!2/5实现代码如下:服务端代码:importjava.io.*;importjava.net.*;publicclassServerTest3{publicstaticvoidmain(String[]args)throwsException{//设置sever端的链接ServerSockets=newServerSocket(8888);Sockets1=s.accept();//sever等待链接System.out.println(s1.getInetAddress().getHostAddress()+上线了);//实例化输出流DataOutputStreamdos=newDataOutputStream(s1.getOutputStream());//实例化输入流DataInputStreamdis=newDataInputStream(s1.getInputStream());//实例化两个线程的对象Threadmsr=newMyServerReader(dis);Threadmsw=newMyServerWriter(dos);//启动线程msr.start();msw.start();}}//创建一个线程用来进行接收,读取数据classMyServerReaderextendsThread{privateDataInputStreamdis;publicMyServerReader(DataInputStreamdis){this.dis=dis;}3/5publicvoidrun(){Stringmsg;try{while(true){msg=dis.readUTF();System.out.println(客户端说:+msg);if(msg.equals(bye)){System.out.println(客户端下线,程序退出);System.exit(0);}}}catch(IOExceptione){System.out.println(e);}}}//创建一个进程用来写入并发送数据classMyServerWriterextendsThread{privateDataOutputStreamdos;publicMyServerWriter(DataOutputStreamdos){this.dos=dos;}publicvoidrun(){BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));Stringmsg;try{while(true){msg=br.readLine();dos.writeUTF(msg);if(msg.equals(bye)){System.out.println(自己下线,程序退出);System.exit(0);}}}catch(IOExceptione){System.out.println(e);}}}4/5客户端代码:importjava.io.*;importjava.net.*;publicclassClientTest3{publicstaticvoidmain(String[]args)throwsException,Exception{//链接sever端Sockets1=newSocket(127.0.0.1,8888);//实例化输入流DataInputStreamdis=newDataInputStream(s1.getInputStream());//实例化输出流DataOutputStreamdos=newDataOutputStream(s1.getOutputStream());//实例化两个进程Threadmcr=newMyClientReader(dis);Threadmcw=newMyClientWriter(dos);//启动两个进程mcr.start();mcw.start();}}//创建一个线程用来进行接收读取数据classMyClientReaderextendsThread{privateDataInputStreamdis;publicMyClientReader(DataInputStreamdis){this.dis=dis;}publicvoidrun(){Stringmsg;try{while(true){msg=dis.readUTF();System.out.println(服务端说:+msg);if(msg.equals(bye)){System.out.println(服务端下线,程序退出);System.exit(0);}}}catch(IOExceptione){5/5System.out.println(e);}}}//创建一个进程用来写入并发送数据classMyClientWriterextendsThread{privateDataOutputStreamdos;publicMyClientWriter(DataOutputStreamdos){this.dos=dos;}@Overridepublicvoidrun(){BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));Stringmsg;try{while(true){msg=br.readLine();dos.writeUTF(msg);if(msg.equals(bye)){System.out.println(自己下线,程序退出);System.exit(0);}}}catch(IOExceptione){System.out.println(e);}}}
本文标题:Java-Socket聊天室完整源代码
链接地址:https://www.777doc.com/doc-6022832 .html