HTML5 WebSocket如何实现点对点聊天
沉沙 2018-07-25 来源 : 阅读 1537 评论 0

摘要:本篇教程探讨了HTML5 WebSocket如何实现点对点聊天,希望阅读本篇文章以后大家有所收获,帮助大家对HTML5的理解更加深入。

本篇教程探讨了HTML5 WebSocket如何实现点对点聊天,希望阅读本篇文章以后大家有所收获,帮助大家对HTML5的理解更加深入。

 

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="//www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="//java.sun.com/xml/ns/javaee

//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);//注意格式

}


通过以上代码,就可以实现一个点对点的聊天功能,如果做的大,可以做成一个web版的聊天系统,包括聊天室和单人聊天,都说websocket不支持二进制的传输。

 

本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标WEB前端HTML5/CSS3频道!

本文由 @沉沙 发布于职坐标。未经许可,禁止转载。
喜欢 | 0 不喜欢 | 0
看完这篇文章有何感觉?已经有0人表态,0%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved

208小时内训课程