HTML5 WebSocket實(shí)現(xiàn)點(diǎn)對(duì)點(diǎn)聊天的示例代碼

昨天使用HTML5的websocket與Tomcat實(shí)現(xiàn)了多人聊天,那是最簡(jiǎn)單也是最基本的,其中注意的就是開(kāi)發(fā)環(huán)境,要滿足jdk1.7和tomcat8,當(dāng)然了tom7 的7.063也行!
今天是國(guó)慶的最后一天,苦逼的加班,繼續(xù)搞代碼!令人欣慰的是,我用google找到了關(guān)于websocket的點(diǎn)對(duì)點(diǎn)聊天,更好的是可以和大多數(shù)系統(tǒng)很好的配合起來(lái)看下效果圖
因?yàn)槭悄M的,這里給出的是兩個(gè)JSP頁(yè)面A和B,里面分別向session里放了兩個(gè)名字小明和小化,注意,這里的session是HttpSession session,之前多人聊天里的session是javax.websocket.Session;不一樣的。
這里想一下, 使用HttpSession session控制聊天的用戶(hù),好處怎樣,自己猜~~~
這里沒(méi)有使用注解,傳統(tǒng)的web.xml配置方式,首先在系統(tǒng)啟動(dòng)的時(shí)候調(diào)用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; } }
這里你可以跟自己的系統(tǒng)結(jié)合,對(duì)應(yīng)的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><!--方法執(zhí)行的級(jí)別--> </servlet> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
這就是最普通的前臺(tái)像后臺(tái)發(fā)送請(qǐng)求的過(guò)程,也是很容易嵌入到自己的系統(tǒng)里
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("用戶(hù)" + 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 { //用戶(hù)所發(fā)消息處理后的map HashMap<String,String> messageMap = MessageUtil.getMessage(msg); //處理消息類(lèi) //上線用戶(hù)集合類(lèi)map HashMap<String, MessageInbound> userMsgMap = InitServlet.getSocketList(); String fromName = messageMap.get("fromName"); //消息來(lái)自人 的userId String toName = messageMap.get("toName"); //消息發(fā)往人的 userId //獲取該用戶(hù) MessageInbound messageInbound = userMsgMap.get(toName); //在倉(cāng)庫(kù)中取出發(fā)往人的MessageInbound MessageInbound messageFromInbound = userMsgMap.get(fromName); if(messageInbound!=null && messageFromInbound!=null){ //如果發(fā)往人 存在進(jìn)行操作 WsOutbound outbound = messageInbound.getWsOutbound(); WsOutbound outFromBound = messageFromInbound.getWsOutbound(); String content = messageMap.get("content"); //獲取消息內(nèi)容 String msgContentString = fromName + "說(shuō): " + content; //構(gòu)造發(fā)送的消息 //發(fā)出去內(nèi)容 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); //登錄的用戶(hù)注冊(cè)進(jìn)去 if(name!=null){ InitServlet.getSocketList().put(name, this);//存放客服ID與用戶(hù) } } @Override public int getReadTimeout() { return 0; } }
在onTextMessage中處理前臺(tái)發(fā)出的信息,并封裝信息傳給目標(biāo)
還有一個(gè)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; } }
當(dāng)然了,前臺(tái)也要按照規(guī)定的格式傳信息
<%@ 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; //發(fā)給誰(shuí) var content = document.getElementById('writeMsg').value; //發(fā)送內(nèi)容 ws.send(fromName+","+toName+","+content);//注意格式 } </script> </head> <body onload="startWebSocket();"> <p>聊天功能實(shí)現(xiàn)</p> 登錄狀態(tài): <span id="denglu" style="color:red;">正在登錄</span> <br> 登錄人: <span id="userName"></span> <br> <br> <br> 發(fā)送給誰(shuí):<input type="text" id="name" value="小明"></input> <br> 發(fā)送內(nèi)容:<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頁(yè)面,B同上
通過(guò)以上代碼,就可以實(shí)現(xiàn)一個(gè)點(diǎn)對(duì)點(diǎn)的聊天功能,如果做的大,可以做成一個(gè)web版的聊天系統(tǒng),包括聊天室和單人聊天,都說(shuō)websocket不支持二進(jìn)制的傳輸,但是看到個(gè)大流說(shuō)了這樣的話
不過(guò)現(xiàn)在做下來(lái) 感覺(jué)使用二進(jìn)制的意義不是很大。很久以前就一直困混,怎么都說(shuō)JS不支持二進(jìn)制,發(fā)現(xiàn)其實(shí)只是一堆坑貨對(duì)這個(gè)沒(méi)研究。。(用的是filereader)
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
HTML5 WebSocket權(quán)威指南 PDF掃描版[75MB]
本書(shū)系統(tǒng)、全面地講解了HTML5WebSocket的各個(gè)方面,是Web開(kāi)發(fā)人員和架構(gòu)師學(xué)習(xí)WebSocket的最佳選擇,內(nèi)容包括:WebSocketAPI和協(xié)議、WebSocket協(xié)議通信的例子、WebSocket的2016-12-22HTML5-WebSocket實(shí)現(xiàn)聊天室示例
本篇文章主要介紹了HTML5-WebSocket實(shí)現(xiàn)聊天室示例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。2016-12-15- 這篇文章主要介紹了淺析HTML5的WebSocket與服務(wù)器推送事件,WebSocket API最大的特點(diǎn)就是讓服務(wù)器和客戶(hù)端能在給定的時(shí)間范圍內(nèi)的任意時(shí)刻,相互推送信息,需要的朋友可以參2016-02-19
html5的websockets全雙工通信詳解學(xué)習(xí)示例
本文主要研究HTML5 WebSockets的使用方法,它是HTML5中最強(qiáng)大的通信功能,定義了一個(gè)全雙工的通信信道,只需Web上的一個(gè)Socket即可進(jìn)行通信,能減少不必要的網(wǎng)絡(luò)流量并降低2014-02-26利用html5的websocket實(shí)現(xiàn)websocket聊天室
利用html5的websocket實(shí)現(xiàn)一個(gè)聊天室,大家可以參考使用2013-12-12html5-websocket基于遠(yuǎn)程方法調(diào)用的數(shù)據(jù)交互實(shí)現(xiàn)
一般在傳統(tǒng)網(wǎng)頁(yè)中注冊(cè)用戶(hù)信息都是通過(guò)post或ajax提交到頁(yè)面處理,到了HTML5后我們有另一種方法就是通過(guò)websocket進(jìn)行數(shù)據(jù)交互,接下來(lái)將詳細(xì)介紹,需要了解的朋友可以參考下2012-12-04HTML5+WebSocket實(shí)現(xiàn)多文件同時(shí)上傳的實(shí)例
本篇文章主要介紹了HTML5-WebSocket實(shí)現(xiàn)多文件同時(shí)上傳的實(shí)例,HTML5結(jié)合Websocket進(jìn)行文件的傳輸就變得更加方便和靈活,有興趣的可以了解一下。2016-12-29帶你認(rèn)識(shí)HTML5中的WebSocket
這篇文章主要介紹了帶你認(rèn)識(shí)HTML5中的WebSocket,本文講解了HTML5 中的 WebSocket API 是個(gè)什么東東、HTML5 中的 WebSocket API 的用法、帶Socket.IO的WebSocket、NodeJS和S2015-05-22HTML5實(shí)現(xiàn)WebSocket協(xié)議原理淺析
這篇文章主要為大家介紹了HTML5實(shí)現(xiàn)WebSocket協(xié)議原理,可以幫助初學(xué)者理解WebSocket協(xié)議,需要的朋友可以參考下2014-07-07HTML5中的websocket實(shí)現(xiàn)直播功能
這篇文章主要介紹了基于HTML5中的websocket實(shí)現(xiàn)直播功能,本文附有源碼,感興趣的朋友跟隨腳本之家小編一起看看吧2018-05-21