package com.ibcio;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import org.apache.catalina.websocket.StreamInbound;
@WebServlet(urlPatterns = { "/message"})
//如果要接收浏览器的ws://协议的请求就必须实现WebSocketServlet这个类
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");
}
//跟平常Servlet不同的是,需要实现createWebSocketInbound,在这里初始化自定义的WebSocket连接对象
@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());
}
}
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 {
//保存连接的MAP容器
private static final Map connections = new HashMap();
//向连接池中添加连接
public static void addMessageInbound(WebSocketMessageInbound inbound){
//添加连接
System.out.println("user : " + inbound.getUser() + " join..");
connections.put(inbound.getUser(), inbound);
}
//获取所有的在线用户
public static Set 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 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();
}
}
}
<%@ 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);
%>
WebSocket 聊天室
WebSocket聊天室
通过HTML5标准提供的API与Ext富客户端框架相结合起来,实现聊天室,有以下特点:
- 实时获取数据,由服务器推送,实现即时通讯
- 利用WebSocket完成数据通讯,区别于轮询,长连接等技术,节省服务器资源
- 结合Ext进行页面展示
- 用户上线下线通知
页面的展示主要是在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 : [
'',
' '],
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;
//初始话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));
//output.receive(message);
input.setValue('');
}
} else {
Ext.Msg.alert('提示', '您已经掉线,无法发送消息!');
}
}
});
上面的代码就是页面完成加载后自动连接服务器,并创建展示界面的代码。