您好,欢迎访问三七文档
当前位置:首页 > 商业/管理/HR > 广告经营 > 使用JavaWebwebSocket实现简易的点对点聊天功能实例代码
使用JavaWebwebSocket实现简易的点对点聊天功能实例代码首先给大家声明一点:需要jdk7,tomcat需要支持websocket的版本1.InitServlet该类主要是用来初始化构造将来存储用户身份信息的map仓库,利用其初始化方法Init初始化仓库,利用其静态方法getSocketList获得对应的用户身份信息。webSocket,我认为MessageInbound用来识别登录人的信息,用它来找到对应的人,推送消息。每次登录都会产生一个MessageInbound。这里的HashMapString,MessageInbound:string存储用户session的登录id,MessageInbound存储推送需要的身份信息。以上属于个人口头话理解。1234567891011121314151617181920212223242526packagesocket;importjava.nio.CharBuffer;importjava.util.ArrayList;importjava.util.HashMap;importjava.util.List;importjavax.servlet.ServletConfig;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;importorg.apache.catalina.websocket.MessageInbound;publicclassInitServletextendsHttpServlet{privatestaticfinallongserialVersionUID=-L;//privatestaticListMessageInboundsocketList;privatestaticHashMapString,MessageInboundsocketList;publicvoidinit(ServletConfigconfig)throwsServletException{//InitServlet.socketList=newArrayListMessageInbound();InitServlet.socketList=newHashMapString,MessageInbound();super.init(config);System.out.println(Serverstart============);}publicstaticHashMapString,MessageInboundgetSocketList(){returnInitServlet.socketList;}/*publicstaticListMessageInboundgetSocketList(){returnInitServlet.socketList;}*/}2.MyWebSocketServletwebsocket用来建立连接的servlet,建立连接时,首先在session获取该登录人的userId,在调用MyMessageInbound构造函数传入userId12packagesocket;importjava.io.IOException;3456789101112131415161718192021222324252627282930313233importjava.io.PrintWriter;importjava.nio.CharBuffer;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importorg.apache.catalina.websocket.StreamInbound;importorg.apache.catalina.websocket.WebSocketServlet;/****@ClassName:MyWebSocketServlet*@Description:建立连接时创立*@authormangues*@date--*/publicclassMyWebSocketServletextendsWebSocketServlet{publicStringgetUser(HttpServletRequestrequest){StringuserName=(String)request.getSession().getAttribute(user);if(userName==null){returnnull;}returnuserName;//return(String)request.getAttribute(user);}@OverrideprotectedStreamInboundcreateWebSocketInbound(Stringarg,HttpServletRequestrequest){System.out.println(##########);returnnewMyMessageInbound(this.getUser(request));}}3.onOpen方法调用InitServlet的map身份仓库,放入用户userId和对应该登录用户的websocket身份信息MessageInbound(可以用userId来寻找到推送需要的身份MessageInbound)onTextMessage:用来获取消息,并发送消息12345678packagesocket;importjava.io.IOException;importjava.nio.ByteBuffer;importjava.nio.CharBuffer;importjava.util.HashMap;importorg.apache.catalina.websocket.MessageInbound;importorg.apache.catalina.websocket.WsOutbound;importutil.MessageUtil;910111213141516171819202122232425262728293031323334353637383940414243444546474849505152publicclassMyMessageInboundextendsMessageInbound{privateStringname;publicMyMessageInbound(){super();}publicMyMessageInbound(Stringname){super();this.name=name;}@OverrideprotectedvoidonBinaryMessage(ByteBufferarg)throwsIOException{//TODOAuto-generatedmethodstub}@OverrideprotectedvoidonTextMessage(CharBuffermsg)throwsIOException{//用户所发消息处理后的mapHashMapString,StringmessageMap=MessageUtil.getMessage(msg);//处理消息类//上线用户集合类mapHashMapString,MessageInbounduserMsgMap=InitServlet.getSocketList();StringfromName=messageMap.get(fromName);//消息来自人的userIdStringtoName=messageMap.get(toName);//消息发往人的userId//获取该用户MessageInboundmessageInbound=userMsgMap.get(toName);//在仓库中取出发往人的MessageInboundif(messageInbound!=null){//如果发往人存在进行操作WsOutboundoutbound=messageInbound.getWsOutbound();Stringcontent=messageMap.get(content);//获取消息内容StringmsgContentString=fromName++content;//构造发送的消息//发出去内容CharBuffertoMsg=CharBuffer.wrap(msgContentString.toCharArray());outbound.writeTextMessage(toMsg);//outbound.flush();}/*for(MessageInboundmessageInbound:InitServlet.getSocketList()){CharBufferbuffer=CharBuffer.wrap(msg);WsOutboundoutbound=messageInbound.getWsOutbound();outbound.writeTextMessage(buffer);outbound.flush();}*/}@OverrideprotectedvoidonClose(intstatus){InitServlet.getSocketList().remove(this);super.onClose(status);53545556575859606162}@OverrideprotectedvoidonOpen(WsOutboundoutbound){super.onOpen(outbound);//登录的用户注册进去if(name!=null){InitServlet.getSocketList().put(name,this);}//InitServlet.getSocketList().add(this);}}4.消息处理类,处理前端发来的消息123456789101112131415161718192021packageutil;importjava.nio.CharBuffer;importjava.util.HashMap;/****@ClassName:MessageUtil*@Description:消息处理类*@authormangues*@date--*/publicclassMessageUtil{publicstaticHashMapString,StringgetMessage(CharBuffermsg){HashMapString,Stringmap=newHashMapString,String();StringmsgString=msg.toString();Stringm[]=msgString.split(,);map.put(fromName,m[]);map.put(toName,m[]);map.put(content,m[]);returnmap;}}5.web配置123456789?xmlversion=1.0encoding=UTF-8?web-appversion=3.0xmlns=:xsi=:schemaLocation=://java.sun.com/xml/ns/javaee/web-app_3_0.xsdservletservlet-namemywebsocket/serv
本文标题:使用JavaWebwebSocket实现简易的点对点聊天功能实例代码
链接地址:https://www.777doc.com/doc-2687045 .html