HTML5 WebSocket实现点对点聊天的示例代码
昨天使用html5的websocket与tomcat实现了多人聊天,那是最简单也是最基本的,其中注意的就是开发环境,要满足jdk1.7和tomcat8,当然了tom7 的7.063也行!
今天是国庆的最后一天,苦逼的加班,继续搞代码!令人欣慰的是,我用google找到了关于websocket的点对点聊天,更好的是可以和大多数系统很好的配合起来看下效果图
因为是模拟的,这里给出的是两个jsp页面a和b,里面分别向session里放了两个名字小明和小化,注意,这里的session是httpsession session,之前多人聊天里的session是javax.websocket.session;不一样的。
这里想一下, 使用httpsession session控制聊天的用户,好处怎样,自己猜~~~
这里没有使用注解,传统的web.xml配置方式,首先在系统启动的时候调用initservlet方法
public class initservlet extends httpservlet { private static final long serialversionuid = -3163557381361759907l; private static hashmap<string,messageinbound> socketlist; public void init(servletconfig config) throws servletexception { initservlet.socketlist = new hashmap<string,messageinbound>(); super.init(config); system.out.println("初始化聊天容器"); } public static hashmap<string,messageinbound> getsocketlist() { return initservlet.socketlist; } }
这里你可以跟自己的系统结合,对应的web配置代码如下:
<?xml version="1.0" encoding="utf-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" 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"> <servlet> <servlet-name>websocket</servlet-name> <servlet-class>socket.mywebsocketservlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>websocket</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <servlet> <servlet-name>initservlet</servlet-name> <servlet-class>socket.initservlet</servlet-class> <load-on-startup>1</load-on-startup><!--方法执行的级别--> </servlet> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
这就是最普通的前台像后台发送请求的过程,也是很容易嵌入到自己的系统里
mywebsocketservlet:
public class mywebsocketservlet extends websocketservlet { public string getuser(httpservletrequest request){ string username = (string) request.getsession().getattribute("user"); if(username==null){ return null; } return username; } protected streaminbound createwebsocketinbound(string arg0, httpservletrequest request) { system.out.println("用户" + request.getsession().getattribute("user") + "登录"); return new mymessageinbound(this.getuser(request)); } }
mymessageinbound继承messageinbound
package socket; import java.io.ioexception; import java.nio.bytebuffer; import java.nio.charbuffer; import java.util.hashmap; import org.apache.catalina.websocket.messageinbound; import org.apache.catalina.websocket.wsoutbound; import util.messageutil; public class mymessageinbound extends messageinbound { private string name; public mymessageinbound() { super(); } public mymessageinbound(string name) { super(); this.name = name; } @override protected void onbinarymessage(bytebuffer arg0) throws ioexception { } @override protected void ontextmessage(charbuffer msg) throws ioexception { //用户所发消息处理后的map hashmap<string,string> messagemap = messageutil.getmessage(msg); //处理消息类 //上线用户集合类map hashmap<string, messageinbound> usermsgmap = initservlet.getsocketlist(); string fromname = messagemap.get("fromname"); //消息来自人 的userid string toname = messagemap.get("toname"); //消息发往人的 userid //获取该用户 messageinbound messageinbound = usermsgmap.get(toname); //在仓库中取出发往人的messageinbound messageinbound messagefrominbound = usermsgmap.get(fromname); if(messageinbound!=null && messagefrominbound!=null){ //如果发往人 存在进行操作 wsoutbound outbound = messageinbound.getwsoutbound(); wsoutbound outfrombound = messagefrominbound.getwsoutbound(); string content = messagemap.get("content"); //获取消息内容 string msgcontentstring = fromname + "说: " + content; //构造发送的消息 //发出去内容 charbuffer tomsg = charbuffer.wrap(msgcontentstring.tochararray()); charbuffer frommsg = charbuffer.wrap(msgcontentstring.tochararray()); outfrombound.writetextmessage(frommsg); outbound.writetextmessage(tomsg); // outfrombound.flush(); outbound.flush(); } } @override protected void onclose(int status) { initservlet.getsocketlist().remove(this); super.onclose(status); } @override protected void onopen(wsoutbound outbound) { super.onopen(outbound); //登录的用户注册进去 if(name!=null){ initservlet.getsocketlist().put(name, this);//存放客服id与用户 } } @override public int getreadtimeout() { return 0; } }
在ontextmessage中处理前台发出的信息,并封装信息传给目标
还有一个messageutil
package util; import java.nio.charbuffer; import java.util.hashmap; public class messageutil { public static hashmap<string,string> getmessage(charbuffer msg) { hashmap<string,string> map = new hashmap<string,string>(); string msgstring = msg.tostring(); string m[] = msgstring.split(","); map.put("fromname", m[0]); map.put("toname", m[1]); map.put("content", m[2]); return map; } }
当然了,前台也要按照规定的格式传信息
<%@ page language="java" contenttype="text/html; charset=utf-8" pageencoding="utf-8"%> <!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>index</title> <script type="text/javascript" src="js/jquery-1.7.2.min.js"></script> <%session.setattribute("user", "小化");%> <script type="text/javascript"> var ws = null; function startwebsocket() { if ('websocket' in window) ws = new websocket("ws://localhost:8080/websocketuser/websocket.do"); else if ('mozwebsocket' in window) ws = new mozwebsocket("ws://localhost:8080/websocketuser/websocket.do"); else alert("not support"); ws.onmessage = function(evt) { //alert(evt.data); console.log(evt); // $("#xiaoxi").val(evt.data); setmessageinnerhtml(evt.data); }; function setmessageinnerhtml(innerhtml){ document.getelementbyid('message').innerhtml += innerhtml + '<br/>'; } ws.onclose = function(evt) { //alert("close"); document.getelementbyid('denglu').innerhtml="离线"; }; ws.onopen = function(evt) { //alert("open"); document.getelementbyid('denglu').innerhtml="在线"; document.getelementbyid('username').innerhtml='小化'; }; } function sendmsg() { var fromname = "小化"; var toname = document.getelementbyid('name').value; //发给谁 var content = document.getelementbyid('writemsg').value; //发送内容 ws.send(fromname+","+toname+","+content);//注意格式 } </script> </head> <body onload="startwebsocket();"> <p>聊天功能实现</p> 登录状态: <span id="denglu" style="color:red;">正在登录</span> <br> 登录人: <span id="username"></span> <br> <br> <br> 发送给谁:<input type="text" id="name" value="小明"></input> <br> 发送内容:<input type="text" id="writemsg"></input> <br> 聊天框:<div id="message" style="height: 250px;width: 280px;border: 1px solid; overflow: auto;"></div> <br> <input type="button" value="send" onclick="sendmsg()"></input> </body> </html>
这是a.jsp页面,b同上
通过以上代码,就可以实现一个点对点的聊天功能,如果做的大,可以做成一个web版的聊天系统,包括聊天室和单人聊天,都说websocket不支持二进制的传输,但是看到个大流说了这样的话
不过现在做下来 感觉使用二进制的意义不是很大。很久以前就一直困混,怎么都说js不支持二进制,发现其实只是一堆坑货对这个没研究。。(用的是filereader)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。