背景介紹
近一個月完成了公司的一個項目,負責即時聊天部分
尋找了一下,決定使用websocket,要問原因的話,因為tomcat 自帶相關消息收發的API,用起來方便
閑話少敘,進入實現步驟
使用工具 java 1.6 tomcat 7.0.27以上版本(以下版本不支持websocket),本人使用的是 7.0.42版本
先概括說一下:(看着迷糊沒關系,下面有提供完整源碼,可以下載后運行 ,結合效果自行分析)
先寫一個,消息處理類,繼承 tomcat的catalina.jar的MessageInbound類,並創建一個構造方法獲取登錄名
繼承onPen,onClose等方法對用戶上線下線進行監聽,重寫onTextMessage(CharBuffer msg)方法,
實現消息的處理,接收和發送
再寫一個網頁應用必須的servlet類接收界面請求,繼承WebSocketServlet類,實現登陸監控
既然是即時聊天,則需要知道在線用戶有哪些,則需要一個在線用戶容器類
另外,消息send(),參數只有一個,所以里面會包含消息發送者和消息接收者,需要解析,所以寫了一個解析類
那么開始詳細代碼解釋
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.getSocketMap(); String fromName = messageMap.get("fromName"); // 消息來源 String toName = messageMap.get("toName"); // 消息接收人 //獲取該用戶 MessageInbound messageInbound = userMsgMap.get(toName); //在容器中獲得接收人的MessageInbound MessageInbound messageFromInbound = userMsgMap.get(fromName); //在容器中獲得發送人的MessageInbound 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.getSocketMap().remove(this); super.onClose(status); } @Override protected void onOpen(WsOutbound outbound) { super.onOpen(outbound); // if(name!=null){ // 用戶登錄后,存入在線用戶容器 InitServlet.getSocketMap().put(name, this); } } @Override public int getReadTimeout() { return 0; } }
然后是 請求接收類
package socket; import javax.servlet.http.HttpServletRequest; import org.apache.catalina.websocket.StreamInbound; import org.apache.catalina.websocket.WebSocketServlet; public class MyWebSocketServlet extends WebSocketServlet { /** * */ private static final long serialVersionUID = -6488889268352650321L; public String getUser(HttpServletRequest request){ String userName = (String) request.getSession().getAttribute("user"); if(userName==null){ return null; } return userName; } @Override protected StreamInbound createWebSocketInbound(String arg0, HttpServletRequest request) { System.out.println("用戶" + request.getSession().getAttribute("user") + "登錄"); return new MyMessageInbound(this.getUser(request)); } }
在線用戶容器初始化類
package socket; import java.util.HashMap; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import org.apache.catalina.websocket.MessageInbound; /** * 應用啟動時加載此類 * 初始化servlet * 在應用啟動后 在線用戶的容器就准備好了! * @author masan * */ public class InitServlet extends HttpServlet { private static final long serialVersionUID = 5772968684237694231L; // 在線用戶容器 (存儲在線用戶 鍵值對 name:MessageInbound) private static HashMap<String,MessageInbound> socketMap; public void init(ServletConfig config) throws ServletException { InitServlet.socketMap = new HashMap<String,MessageInbound>(); super.init(config); System.out.println("Server Started!"); } /** * 獲取在線用戶容器的方法 * @return */ public static HashMap<String,MessageInbound> getSocketMap() { return InitServlet.socketMap; } }
然后是 消息體的解析類,我是按照逗號分隔的 前兩處分別為發送者和接收者姓名,后一處為消息內容
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; } }
那么附上工程目錄結構:
附上三個JSP的內容
<%@ 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>
<%@ 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) { console.log(evt); //alert(evt.data); //$("#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>
附上兩個JSP,可自行增加,
另:附上web.xml ,相當重要,里面進行了servlet配置,並且設置了要求
initServlet在應用啟動時就要執行
<?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>
注意事項:1.js代碼內的websocket 構造參數里的IP 要和最終瀏覽器訪問地址一致 要么都是localhost要么都是IP 否則跨域
2.這個demo內是根據用戶名識別用戶的,明顯不能做到唯一,所以只能是個demo,要用到項目里,請考慮下然后稍作修改即可
(我生產項目里用的mysql數據庫,最后使用的用戶ID來做區別)
3.消息發送參數只有一個,那么發送者和接收者的信息一並發送,后台有個解析類,如果需要傳遞其他參數,可自行修改解析類的解析方案
完整代碼下載地址
想免積分下載的,但是CSDN最新修改,沒有零分的了,最低1分
http://download.csdn.net/download/u012580998/9941412
增加百度雲盤下載地址
https://pan.baidu.com/s/1o7W6yW6