您好,欢迎访问三七文档
当前位置:首页 > 商业/管理/HR > 广告经营 > java-socket使用TCP协议实现的聊天室
1.Socket服务器端importjava.io.DataInputStream;importjava.io.DataOutputStream;importjava.io.IOException;importjava.net.ServerSocket;importjava.net.Socket;importjava.util.Enumeration;importjava.util.Hashtable;importjava.util.Iterator;importjava.util.Scanner;publicclassServerimplementsRunnable{privatestaticServerSocketserver;privatestaticSocketsocket=null;//信息存储器privateHashtableString,SocketinfoMemory=newHashtableString,Socket();privateDataInputStreamdis;privateDataOutputStreamdos;publicvoidrun(){//监听信息的方法listenLink();}//监听信息privatevoidlistenLink(){try{while(true){dis=newDataInputStream(socket.getInputStream());Stringstr=dis.readUTF();System.out.println(str);this.analyseMes(str);}}catch(IOExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}}//数据分析器,给予相应处理privatevoidanalyseMes(Stringmes){String[]n=mes.split(:);Stringname1=null;Stringmessage=;if(n.length1){for(inti=0;in.length;i++){name1=n[0];if(i!=0){message+=n[i];}}socket=infoMemory.get(name1);}System.out.println(message);//-quit:接受客户端退出信息//将该用户的退出信息转发至所有在线成员if(message.trim().equalsIgnoreCase(-quit)){System.out.println(name1+//+socket+quit!);transforMes(*+name1+退出聊天室);Socketsk=infoMemory.get(name1);transforMesSingle(sk,name1+-quit);try{sk.close();}catch(IOExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}infoMemory.remove(name1);if(infoMemory.size()=1){@SuppressWarnings(rawtypes)Iteratoriter=infoMemory.keySet().iterator();Stringkey=(String)iter.next();socket=infoMemory.get(key);}}//-getList:接受客户端获取列表的请求//将所有用户连接为字符串的形式,如:-getList,用户1,用户2...用户nelseif(message.trim().equals(-getList)){StringBufferlist=newStringBuffer();list.append(-getList,);EnumerationStringnames=infoMemory.keys();while(names.hasMoreElements()){list.append(names.nextElement()+,);}transforMesSingle(socket,list.toString());}//-to:接受客户端请求,将信息转发给相应客户//如果目标客户不存在,则向请求客户发送相应消息elseif(message.indexOf(-to)!=-1&&message.startsWith(-to)){Stringmain=message.substring(-to.length(),message.length());System.out.println(main);StringtoName=main.substring(0,main.indexOf());Stringname=this.getConsumerName(socket);Stringcon=name+对你说(私聊):+main.substring(toName.length()+1,main.length());if(!infoMemory.containsKey(toName))transforMesSingle(socket,发送用户不存在,发送对象时请使用正确的用户名(可输入-getList获取在线好友));elsetransforMesSingle(infoMemory.get(toName),con);}//-nick:接受客户端登录请求//如果输入的匿名不存在,则登记该用户与infoMemory//如果存在则返回相应提示elseif(mes.indexOf(-nick)!=-1&&mes.startsWith(-nick)){StringnickName=mes.substring(-nick.length(),mes.length());if(infoMemory.containsKey(nickName))transforMesSingle(socket,-nick:你的呢称已经存在,请使用其他呢称.);else{infoMemory.put(nickName,socket);transforMes(欢迎+nickName+来到聊天室!);System.out.println(nickName+//+socket.toString()+在线.);System.out.println(infoMemory.size());}}//一般消息将会转发至所有用户else{transforMes(name1+说:+message);}}//信息发送多人publicvoidtransforMes(Stringmes){EnumerationSocketall=infoMemory.elements();try{while(all.hasMoreElements()){Sockets=all.nextElement();dos=newDataOutputStream(s.getOutputStream());dos.writeUTF(mes);}}catch(Exceptions){}}//信息发送单人privatevoidtransforMesSingle(Sockets,Stringmes){try{dos=newDataOutputStream(s.getOutputStream());dos.writeUTF(mes);}catch(IOExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}}//通过地址得到用户的昵称由于Hashtable无法通过Value获取Key,所有专门写该方法privateStringgetConsumerName(Socketsa){EnumerationStringnames=infoMemory.keys();Stringname=null;while(names.hasMoreElements()){Stringtemp=names.nextElement();Socketadrs=infoMemory.get(temp);//进行比较if(sa.equals(adrs)){name=temp;break;}}returnname;}publicstaticvoidmain(String[]args){Serverser=newServer();Scannerinput=newScanner(System.in);System.out.println(请输入服务器的命令(-run/-quit));Stringcommand=null;//equalsIgnoreCase()将此String与另一个String//比较,不考虑大小写。如果两个字符串的长度相同,并且其中的相应字符都相等(忽略大小写),则认为这两个字符串是相等的。while(!(command=input.next()).equalsIgnoreCase(-quit)){//获取帮助信息if(command.equalsIgnoreCase(-help)){ser.helpList();}if(command.equalsIgnoreCase(-run)){try{server=newServerSocket(8888);booleangoon=true;//测试服务器创建,如果成功则同时为信息监听器建立线程System.out.println(!-创建服务器并运行...);while(goon){socket=server.accept();newThread(ser).start();}}catch(IOExceptione1){//TODOAuto-generatedcatchblocke1.printStackTrace();}}}}//显示帮助信息publicvoidhelpList(){System.out.println(-help+获取服务器相应操作的帮助+\n+-run+运行服务器,并同时建立信息监听+\n);}}2.Socket客户端importjava.io.DataInputStream;importjava.io.DataOutputStream;importjava.io.IOException;importjava.net.Socket;importjava.util.Scanner;publicclassClientimplementsRunnable{privatestaticSocketsocket=null;//用来测试用户名是否正确在checkNickName中会用到.并穿插在sendMes方法中privatebooleantest=true;privateDataInputStreamdis;privateDataOutputStreamdos;privatestaticStringname=null;publicvoidrun(){getMessage();}//接收数据privatevoidgetMessage(){try{while(true){dis=newDataInputStream(socket.getInputStream());Stringmes=dis.readUTF();if(mes.indexOf(-getList)==0)this.getList(mes);elseif(mes.endsWith(name+-quit)){socket.close();}else{System.out.println(mes);}}}catch(IOExceptione){System.out.println(接受信息失败);}}//接收一次数据publicStringgetMesOnce(){Stringmes=null;try{dis=newDataInputStream(sock
本文标题:java-socket使用TCP协议实现的聊天室
链接地址:https://www.777doc.com/doc-4499014 .html