您好,登錄后才能下訂單哦!
這期內容當中小編將會給大家帶來有關怎么在HTML5中利用WebSocket實現點對點聊天,文章內容豐富且以專業的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
首先在系統啟動的時候調用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>
上述就是小編為大家分享的怎么在HTML5中利用WebSocket實現點對點聊天了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。