前言
HTML5 WebSocket實現了服務器與瀏覽器的雙向通信,雙向通信使服務器消息推送開發更加簡單,最多見的就是即時通信和對信息實時性要求比較高的應用。之前的服務器消息推送大部分採用的都是「輪詢」和「長鏈接」技術,這兩中技術都會對服務器產生至關大的開銷,並且實時性不是特別高。WebSocket技術對只會產生很小的開銷,而且實時性特別高。下面就開始講解如何利用WebSocket技術開發聊天室。在這個實例中,採用的是Tomcat7服務器,每一個服務器對於WebSocket的實現都是不同的,因此這個實例只能在Tomcat服務器中運行,不過目前Spring已經推出了WebSocket的API,可以兼容各個服務器的實現,你們能夠查閱相關的資料進行了解,在這裏就不介紹了,下圖是聊天室的效果圖:
在這裏實例中,實現了消息的實時推送,還實現了聊天用戶的上下線通知。下面就開始具體講解如何實現。
後臺處理
Tomcat實現WebSocket的主要是依靠org.apache.catalina.websocket.MessageInbound這個類,這個類的在{TOMCAT_HOME}/lib/catalina.jar中,因此你開發的時候須要將catalina.jar和tomcat-coyote.jar引入進來,下面這段代碼就是暴露給客戶端鏈接地址的Servlet:
- package com.ibcio;
-
- import javax.servlet.annotation.WebServlet;
- import javax.servlet.http.HttpServletRequest;
-
- import org.apache.catalina.websocket.StreamInbound;
-
- @WebServlet(urlPatterns = { "/message"})
-
- public class WebSocketMessageServlet extends org.apache.catalina.websocket.WebSocketServlet {
-
- private static final long serialVersionUID = 1L;
-
- public static int ONLINE_USER_COUNT = 1;
-
- public String getUser(HttpServletRequest request){
- return (String) request.getSession().getAttribute("user");
- }
-
-
- @Override
- protected StreamInbound createWebSocketInbound(String subProtocol,HttpServletRequest request) {
- return new WebSocketMessageInbound(this.getUser(request));
- }
- }
這個Servlet跟普通的Servlet有些不一樣,繼承的WebSocketServlet類,而且要重寫createWebSocketInbound方法。這個類中Session中的user屬性是用戶進入index.jsp的時候設置的,記錄當前用戶的暱稱。下面就是本身實現的WebSocket鏈接對象類WebSocketMessageInbound類的代碼:
- package com.ibcio;
-
- import java.io.IOException;
- import java.nio.ByteBuffer;
- import java.nio.CharBuffer;
-
- import net.sf.json.JSONObject;
-
- import org.apache.catalina.websocket.MessageInbound;
- import org.apache.catalina.websocket.WsOutbound;
-
- public class WebSocketMessageInbound extends MessageInbound {
-
-
- private final String user;
-
- public WebSocketMessageInbound(String user) {
- this.user = user;
- }
-
- public String getUser() {
- return this.user;
- }
-
-
- @Override
- protected void onOpen(WsOutbound outbound) {
-
- JSONObject result = new JSONObject();
- result.element("type", "user_join");
- result.element("user", this.user);
-
- WebSocketMessageInboundPool.sendMessage(result.toString());
-
- result = new JSONObject();
- result.element("type", "get_online_user");
- result.element("list", WebSocketMessageInboundPool.getOnlineUser());
-
- WebSocketMessageInboundPool.addMessageInbound(this);
-
- WebSocketMessageInboundPool.sendMessageToUser(this.user, result.toString());
- }
-
- @Override
- protected void onClose(int status) {
-
- WebSocketMessageInboundPool.removeMessageInbound(this);
- JSONObject result = new JSONObject();
- result.element("type", "user_leave");
- result.element("user", this.user);
-
- WebSocketMessageInboundPool.sendMessage(result.toString());
- }
-
- @Override
- protected void onBinaryMessage(ByteBuffer message) throws IOException {
- throw new UnsupportedOperationException("Binary message not supported.");
- }
-
-
- @Override
- protected void onTextMessage(CharBuffer message) throws IOException {
-
- WebSocketMessageInboundPool.sendMessage(message.toString());
- }
- }
代碼中的主要實現了onOpen、onClose、onTextMessage方法,分別處理用戶上線、下線、發送消息。在這個類中有個WebSocketMessageInboundPool鏈接池類,這個類是用來管理目前在線的用戶的鏈接,下面是這個類的代碼:
- package com.ibcio;
-
- import java.io.IOException;
- import java.nio.CharBuffer;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.Set;
-
- public class WebSocketMessageInboundPool {
-
-
- private static final Map<String,WebSocketMessageInbound > connections = new HashMap<String,WebSocketMessageInbound>();
-
-
- public static void addMessageInbound(WebSocketMessageInbound inbound){
-
- System.out.println("user : " + inbound.getUser() + " join..");
- connections.put(inbound.getUser(), inbound);
- }
-
-
- public static Set<String> getOnlineUser(){
- return connections.keySet();
- }
-
- public static void removeMessageInbound(WebSocketMessageInbound inbound){
-
- System.out.println("user : " + inbound.getUser() + " exit..");
- connections.remove(inbound.getUser());
- }
-
- public static void sendMessageToUser(String user,String message){
- try {
-
- System.out.println("send message to user : " + user + " ,message content : " + message);
- WebSocketMessageInbound inbound = connections.get(user);
- if(inbound != null){
- inbound.getWsOutbound().writeTextMessage(CharBuffer.wrap(message));
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
-
- public static void sendMessage(String message){
- try {
- Set<String> keySet = connections.keySet();
- for (String key : keySet) {
- WebSocketMessageInbound inbound = connections.get(key);
- if(inbound != null){
- System.out.println("send message to user : " + key + " ,message content : " + message);
- inbound.getWsOutbound().writeTextMessage(CharBuffer.wrap(message));
- }
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
前臺展現
上面的代碼就是聊天室後臺的代碼,主要是由3個對象組成,Servlet、鏈接對象、鏈接池,下面就是前臺的代碼,前臺的代碼主要是實現與服務器進行鏈接,展現用戶列表及信息列表,前臺的展現使用了Ext框架,不熟悉Ext的同窗能夠初步的瞭解下Ext,下面的是index.jsp的代碼:
- <%@ page language="java" pageEncoding="UTF-8" import="com.ibcio.WebSocketMessageServlet"%>
- <%
- String user = (String)session.getAttribute("user");
- if(user == null){
- //爲用戶生成暱稱
- user = "遊客" + WebSocketMessageServlet.ONLINE_USER_COUNT;
- WebSocketMessageServlet.ONLINE_USER_COUNT ++;
- session.setAttribute("user", user);
- }
- pageContext.setAttribute("user", user);
- %>
- <html>
- <head>
- <title>WebSocket 聊天室</title>
-
- <link rel="stylesheet" type="text/css" href="ext4/resources/css/ext-all.css">
- <link rel="stylesheet" type="text/css" href="ext4/shared/example.css" />
- <link rel="stylesheet" type="text/css" href="css/websocket.css" />
-
-
- <script type="text/javascript" src="ext4/ext-all-debug.js"></script>
- <script type="text/javascript" src="websocket.js"></script>
- <script type="text/javascript">
- var user = "${user}";
- </script>
- </head>
-
- <body>
- <h1>WebSocket聊天室</h1>
- <p>經過HTML5標準提供的API與Ext富客戶端框架相結合起來,實現聊天室,有如下特色:</p>
- <ul class="feature-list" style="padding-left: 10px;">
- <li>實時獲取數據,由服務器推送,實現即時通信</li>
- <li>利用WebSocket完成數據通信,區別於輪詢,長鏈接等技術,節省服務器資源</li>
- <li>結合Ext進行頁面展現</li>
- <li>用戶上線下線通知</li>
- </ul>
- <div id="websocket_button"></div>
- </body>
- </html>
頁面的展現主要是在websocket.js中進行控制,下面是websocket.jsd的代碼:
-
- Ext.define('MessageContainer', {
-
- extend : 'Ext.view.View',
-
- trackOver : true,
-
- multiSelect : false,
-
- itemCls : 'l-im-message',
-
- itemSelector : 'div.l-im-message',
-
- overItemCls : 'l-im-message-over',
-
- selectedItemCls : 'l-im-message-selected',
-
- style : {
- overflow : 'auto',
- backgroundColor : '#fff'
- },
-
- tpl : [
- '<div class="l-im-message-warn">交談中請勿輕信匯款、中獎信息、陌生電話。 請遵照相關法律法規。</div>',
- '<tpl for=".">',
- '<div class="l-im-message">',
- '<div class="l-im-message-header l-im-message-header-{source}">{from} {timestamp}</div>',
- '<div class="l-im-message-body">{content}</div>', '</div>',
- '</tpl>'],
-
- messages : [],
-
- initComponent : function() {
- var me = this;
- me.messageModel = Ext.define('Leetop.im.MessageModel', {
- extend : 'Ext.data.Model',
- fields : ['from', 'timestamp', 'content', 'source']
- });
- me.store = Ext.create('Ext.data.Store', {
- model : 'Leetop.im.MessageModel',
- data : me.messages
- });
- me.callParent();
- },
-
-
- receive : function(message) {
- var me = this;
- message['timestamp'] = Ext.Date.format(new Date(message['timestamp']),
- 'H:i:s');
- if(message.from == user){
- message.source = 'self';
- }else{
- message.source = 'remote';
- }
- me.store.add(message);
- if (me.el.dom) {
- me.el.dom.scrollTop = me.el.dom.scrollHeight;
- }
- }
- });
這段代碼主要是實現了展現消息的容器,下面就是頁面加載完成後開始執行的代碼:
- Ext.onReady(function() {
-
- var input = Ext.create('Ext.form.field.HtmlEditor', {
- region : 'south',
- height : 120,
- enableFont : false,
- enableSourceEdit : false,
- enableAlignments : false,
- listeners : {
- initialize : function() {
- Ext.EventManager.on(me.input.getDoc(), {
- keyup : function(e) {
- if (e.ctrlKey === true
- && e.keyCode == 13) {
- e.preventDefault();
- e.stopPropagation();
- send();
- }
- }
- });
- }
- }
- });
-
- var output = Ext.create('MessageContainer', {
- region : 'center'
- });
-
- var dialog = Ext.create('Ext.panel.Panel', {
- region : 'center',
- layout : 'border',
- items : [input, output],
- buttons : [{
- text : '發送',
- handler : send
- }]
- });
- var websocket;
-
-
- function initWebSocket() {
- if (window.WebSocket) {
- websocket = new WebSocket(encodeURI('ws://localhost:8080/WebSocket/message'));
- websocket.onopen = function() {
-
- win.setTitle(title + ' (已鏈接)');
- }
- websocket.onerror = function() {
-
- win.setTitle(title + ' (鏈接發生錯誤)');
- }
- websocket.onclose = function() {
-
- win.setTitle(title + ' (已經斷開鏈接)');
- }
-
- websocket.onmessage = function(message) {
- var message = JSON.parse(message.data);
-
- if (message.type == 'message') {
- output.receive(message);
- } else if (message.type == 'get_online_user') {
-
- var root = onlineUser.getRootNode();
- Ext.each(message.list,function(user){
- var node = root.createNode({
- id : user,
- text : user,
- iconCls : 'user',
- leaf : true
- });
- root.appendChild(node);
- });
- } else if (message.type == 'user_join') {
-
- var root = onlineUser.getRootNode();
- var user = message.user;
- var node = root.createNode({
- id : user,
- text : user,
- iconCls : 'user',
- leaf : true
- });
- root.appendChild(node);
- } else if (message.type == 'user_leave') {
-
- var root = onlineUser.getRootNode();
- var user = message.user;
- var node = root.findChild('id',user);
- root.removeChild(node);
- }
- }
- }
- };
-
-
- var onlineUser = Ext.create('Ext.tree.Panel', {
- title : '在線用戶',
- rootVisible : false,
- region : 'east',
- width : 150,
- lines : false,
- useArrows : true,
- autoScroll : true,
- split : true,
- iconCls : 'user-online',
- store : Ext.create('Ext.data.TreeStore', {
- root : {
- text : '在線用戶',
- expanded : true,
- children : []
- }
- })
- });
- var title = '歡迎您:' + user;
-
- var win = Ext.create('Ext.window.Window', {
- title : title + ' (未鏈接)',
- layout : 'border',
- iconCls : 'user-win',
- minWidth : 650,
- minHeight : 460,
- width : 650,
- animateTarget : 'websocket_button',
- height : 460,
- items : [dialog,onlineUser],
- border : false,
- listeners : {
- render : function() {
- initWebSocket();
- }
- }
- });
-
- win.show();
-
-
- function send() {
- var message = {};
- if (websocket != null) {
- if (input.getValue()) {
- Ext.apply(message, {
- from : user,
- content : input.getValue(),
- timestamp : new Date().getTime(),
- type : 'message'
- });
- websocket.send(JSON.stringify(message));
-
- input.setValue('');
- }
- } else {
- Ext.Msg.alert('提示', '您已經掉線,沒法發送消息!');
- }
- }
- });
上面的代碼就是頁面完成加載後自動鏈接服務器,並建立展現界面的代碼。
注意
須要注意的兩點,在部署完成以後須要將在tomcat應用目錄中的lib目錄下的catalina.jar和tomcat-coyote.jar刪掉,好比項目的lib目錄在D:\workspace\WebSocket\WebRoot\WEB-INF\lib,而部署的應用lib目錄是在D:\tools\apache-tomcat-7.0.32\webapps\WebSocket\WEB-INF\lib,刪掉部署目錄的lib目錄中連兩個jar就能夠了,不然會包
Could not initialize class com.ibcio.WebSocketMessageServlet錯誤,切記。
若是仍是沒法創建鏈接,請下載最新的tomcat,忘了是那個版本的tomcatcreateWebSocketInbound是沒有request參數的,如今的這個代碼是有這個參數了,7.0.3XX版本都是帶這個參數的,切記。
總結
實例下載