HTML5 WebSocket实现点对点聊天的示例代码
HTML5的websocket与Tomcat实现了多人聊天,那是最简单也是最基本的,其中注意的就是开发环境,要满足jdk1.7和tomcat8,当然了tom7的7.063也行,在网站上找到了用google关于websocket的点对点聊天,更好的是可以和大多数系统很好的配合起来看下效果图。
请点击此处输入图片描述
因为是模拟的,这里给出的是两个JSP页面A和B,里面分别向session里放了两个名字小明和小化,注意,这里的session是HttpSessionsession,之前多人聊天里的session是javax.websocket.Session;不一样的。
请点击此处输入图片描述
这里想一下,使用HttpSessionsession控制聊天的用户,这里没有使用注解,传统的web.xml配置方式,首先在系统启动的时候调用InitServlet方法。
publicclassInitServletextendsHttpServlet{
privatestaticfinallongserialVersionUID=-3163557381361759907L;
privatestaticHashMapsocketList;
publicvoidinit(ServletConfigconfig)throwsServletException{
InitServlet.socketList=newHashMap();
super.init(config);
System.out.println("初始化聊天容器");
}
publicstaticHashMapgetSocketList(){
returnInitServlet.socketList;
}
}
这里你可以跟自己的系统结合,对应的web配置代码如下:
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
websocket
socket.MyWebSocketServlet
websocket
*.do
initServlet
socket.InitServlet
1
index.jsp
这就是最普通的前台像后台发送请求的过程,也是很容易嵌入到自己的系统里
MyWebSocketServlet:
publicclassMyWebSocketServletextendsWebSocketServlet{
publicStringgetUser(HttpServletRequestrequest){
StringuserName=(String)request.getSession().getAttribute("user");
if(userName==null){
returnnull;
}
returnuserName;
}
protectedStreamInboundcreateWebSocketInbound(Stringarg0,
HttpServletRequestrequest){
System.out.println("用户"+request.getSession().getAttribute("user")+"登录");
returnnewMyMessageInbound(this.getUser(request));
}
}
MyMessageInbound继承MessageInbound
packagesocket;
importjava.io.IOException;
importjava.nio.ByteBuffer;
importjava.nio.CharBuffer;
importjava.util.HashMap;
importorg.apache.catalina.websocket.MessageInbound;
importorg.apache.catalina.websocket.WsOutbound;
importutil.MessageUtil;
publicclassMyMessageInboundextendsMessageInbound{
privateStringname;
publicMyMessageInbound(){
super();
}
publicMyMessageInbound(Stringname){
super();
this.name=name;
}
@Override
protectedvoidonBinaryMessage(ByteBufferarg0)throwsIOException{
}
@Override
protectedvoidonTextMessage(CharBuffermsg)throwsIOException{
//用户所发消息处理后的map
HashMapmessageMap=MessageUtil.getMessage(msg);//处理消息类
//上线用户集合类map
HashMapuserMsgMap=InitServlet.getSocketList();
StringfromName=messageMap.get("fromName");//消息来自人的userId
StringtoName=messageMap.get("toName");//消息发往人的userId
//获取该用户
MessageInboundmessageInbound=userMsgMap.get(toName);//在仓库中取出发往人的MessageInbound
MessageInboundmessageFromInbound=userMsgMap.get(fromName);
if(messageInbound!=null&&messageFromInbound!=null){//如果发往人存在进行操作
WsOutboundoutbound=messageInbound.getWsOutbound();
WsOutboundoutFromBound=messageFromInbound.getWsOutbound();
Stringcontent=messageMap.get("content");//获取消息内容
StringmsgContentString=fromName+"说:"+content;//构造发送的消息
//发出去内容
CharBuffertoMsg=CharBuffer.wrap(msgContentString.toCharArray());
CharBufferfromMsg=CharBuffer.wrap(msgContentString.toCharArray());
outFromBound.writeTextMessage(fromMsg);
outbound.writeTextMessage(toMsg);//
outFromBound.flush();
outbound.flush();
}
}
@Override
protectedvoidonClose(intstatus){
InitServlet.getSocketList().remove(this);
super.onClose(status);
}
@Override
protectedvoidonOpen(WsOutboundoutbound){
super.onOpen(outbound);
//登录的用户注册进去
if(name!=null){
InitServlet.getSocketList().put(name,this);//存放客服ID与用户
}
}
@Override
publicintgetReadTimeout(){
return0;
}
}
在onTextMessage中处理前台发出的信息,并封装信息传给目标
还有一个messageutil
packageutil;
importjava.nio.CharBuffer;
importjava.util.HashMap;
publicclassMessageUtil{
publicstaticHashMapgetMessage(CharBuffermsg){
HashMapmap=newHashMap();
StringmsgString=msg.toString();
Stringm[]=msgString.split(",");
map.put("fromName",m[0]);
map.put("toName",m[1]);
map.put("content",m[2]);
returnmap;
}
}
当然了,前台也要按照规定的格式传信息
<%@pagelanguage="java"contentType="text/html;charset=UTF-8"
pageEncoding="UTF-8"%>
Index
<%session.setAttribute("user","小化");%>
varws=null;
functionstartWebSocket(){
if('WebSocket'inwindow)
ws=newWebSocket("ws://localhost:8080/WebSocketUser/websocket.do");
elseif('MozWebSocket'inwindow)
ws=newMozWebSocket("ws://localhost:8080/WebSocketUser/websocket.do");
else
alert("notsupport");
ws.onmessage=function(evt){
//alert(evt.data);
console.log(evt);
//$("#xiaoxi").val(evt.data);
setMessageInnerHTML(evt.data);
};
functionsetMessageInnerHTML(innerHTML){
document.getElementById('message').innerHTML+=innerHTML+'
';
}
ws.onclose=function(evt){
//alert("close");
document.getElementById('denglu').innerHTML="离线";
};
ws.onopen=function(evt){
//alert("open");
document.getElementById('denglu').innerHTML="在线";
document.getElementById('userName').innerHTML='小化';
};
}
functionsendMsg(){
varfromName="小化";
vartoName=document.getElementById('name').value;//发给谁
varcontent=document.getElementById('writeMsg').value;//发送内容
ws.send(fromName+","+toName+","+content);//注意格式
}
聊天功能实现
登录状态:
正在登录
登录人:
发送给谁:
发送内容:
聊天框:
这是A.jsp页面,B同上
通过以上代码,就可以实现一个点对点的聊天功能,如果做的大,可以做成一个web版的聊天系统,包括聊天室和单人聊天,都说websocket不支持二进制的传输。以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。