一.案例介绍
案例场景是Dags的tomcat服务端实时向另一个Cloud的tomcat服务端发送消息数据,Cloud服务端接收到消息后,根据用户登录权限,实时向web浏览器页面推送该消息并以弹框展示;这里使用基于JavaEE的 WebSocket方案,需要兼容低版本浏览器的请参考我的上一篇介绍中的参考文献,当然,我也会在下一篇介绍低版本浏览器下使用socketJs的详细案例;下面开始今天的JavaEE+WebSocket案例使用介绍:
1.项目框架是Spring+SpringMVC+Mybatis的结构,我们先实现JavaEE的 WebSocket方案,首先在项目的pom.xml中引入JavaEE的api;
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
2. 封装websocket客户端,其中websocket-sdk.js 和websocket.js分别如下:
(function ($) {
$.config = {
url: '', //链接地址
};
$.init = function (config) {
this.config = config;
return this;
};
/**
* 连接webcocket
*/
$.connect = function () {
var protocol = (window.location.protocol == 'http:') ? 'ws:' : 'wss:';
this.host = protocol + this.config.url;
window.WebSocket = window.WebSocket || window.MozWebSocket;
if (!window.WebSocket) { // 检测浏览器支持
this.error('Error: WebSocket is not supported .');
return;
}
this.socket = new WebSocket(this.host); // 创建连接并注册响应函数
this.socket.onopen = function () {
$.onopen();
};
this.socket.onmessage = function (message) {
$.onmessage(message);
};
this.socket.onclose = function () {
$.onclose();
$.socket = null; // 清理
};
this.socket.onerror = function (errorMsg) {
$.onerror(errorMsg);
}
return this;
}
/**
* 自定义异常函数
* @param {Object} errorMsg
*/
$.error = function (errorMsg) {
this.onerror(errorMsg);
}
/**
* 消息发送
*/
$.send = function (message) {
if (this.socket) {
this.socket.send(message);
return true;
}
this.error('please connect to the server first !!!');
return false;
}
$.close = function () {
if (this.socket != undefined && this.socket != null) {
this.socket.close();
} else {
this.error("this socket is not available");
}
}
/**
* 消息回調
* @param {Object} message
*/
$.onmessage = function (message) {
}
/**
* 链接回调函数
*/
$.onopen = function () {
}
/**
* 关闭回调
*/
$.onclose = function () {
}
/**
* 异常回调
*/
$.onerror = function () {
}
})(ws = {});
websocket.js 如下:
var ip = window.location.host;
var gotoUrl = new StringBuffer();
//访问路径
gotoUrl.append(ip).append(path);
$(function () {
var url = gotoUrl+"/websocketServer/"+loginUserId;
ws.init({
url: url
}).connect();
ws.onmessage = function(message) {
console.log("收到信息:" + message.data);
var msg=JSON.parse(message.data);
//收到服务端消息的处理逻辑(略)
...
}
ws.onopen = function() {
$.onopen();
setInterval(function(){
this.send("socket服务开启中...");
},5000);
};
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
ws.close();
};
});
3.封装的服务端分别为WebSocketServer.java和WebSocketUtils.java,其内容分别如下:
package com.test.web.websocket;
import org.apache.log4j.Logger;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
/**
* @author
* @Description:WebSocket服务端
* @date 2018年11月30日 17:41
*/
@ServerEndpoint(value = "/websocketServer/{loginUserId}")
public class WebSocketServer {
private static Logger log = Logger.getLogger(WebSocketServer.class);
/*
*声明客户端连接进入的方法
*/
@OnOpen
public void onOpen(@PathParam("loginUserId") String loginUserId ,
Session session){
log.info("[WebSocketServer] Connected : loginUserId = "+ loginUserId);
WebSocketUtils.add(loginUserId , session);
}
/*
*消息监听处理方法
*/
@OnMessage
public String onMessage(@PathParam("loginUserId") String loginUserId,
String message) {
log.info("[WebSocketServer] Received Message : loginUserId = "+ loginUserId + " , message = " + message);
if (message.equals("&")){
return "&";
}else{
WebSocketUtils.receive(loginUserId , message);
return "Got your message ("+ message +").";
}
}
/*
*websocket系统异常处理
*/
@OnError
public void onError(@PathParam("loginUserId") String loginUserId,
Throwable throwable,
Session session) {
log.info("[WebSocketServer] Connection Exception : loginUserId = "+ loginUserId + " , throwable = " + throwable.getMessage());
WebSocketUtils.remove(loginUserId);
}
/**
* 关闭连接
*/
@OnClose
public void onClose(@PathParam("loginUserId") String loginUserId,
Session session) {
log.info("[WebSocketServer] Close Connection : loginUserId = " + loginUserId);
WebSocketUtils.remove(loginUserId);
}
}
WebSocketUtils.java文件如下:
package com.test.web.websocket;
import org.apache.log4j.Logger;
import javax.websocket.Session;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author
* @Description:处理方法
* @date 2018年11月30日 17:45
*/
public class WebSocketUtils {
private static Logger log = Logger.getLogger(WebSocketUtils.class);
public static Map<String, Session> clients = new ConcurrentHashMap<String, Session>();
/*
* 添加session,此处可以添加登录权限等处理细节
*/
public static void add(String userId, Session session) {
clients.put(userId, session);
log.info("当前连接数 = " + clients.size());
}
/*
* 接收信息
*/
public static void receive(String userId, String message) {
log.info("收到消息 : UserId = " + userId + " , Message = " + message);
log.info("当前连接数 = " + clients.size());
}
/*
* 去除session
*/
public static void remove(String userId) {
clients.remove(userId);
log.info("当前连接数 = " + clients.size());
}
/*
*获取session并发送消息,实现服务端主动推送方法
*/
public static boolean sendMessage(String userId, String message) {
log.info("当前连接数 = " + clients.size());
if (clients.get(userId) == null) {
return false;
} else {
clients.get(userId).getAsyncRemote().sendText(message);
return true;
}
}
}
4.服务端调用,主动推送消息如下:
JSONObject json = new JSONObject();
// 消息类型: 0 地磁报警 1 黑名单报警
json.put("messageType", LoginConstants.MESSAGE_TYPE_1);
json.put("messageTitle", "黑名单报警");
json.put("messageUrl", "/plateBlackAlarm/init");
json.put("messageContent", msgBo);
//消息id
json.put("messageId",UserCodeUtil.generateCode());
WebSocketUtils.sendMessage(msgBo.getUserId,json.toJSONString());
5.客户端调用如下:
// 消息体JSON 对象 对应JAVA 的 Msg对象
var data = {
// 定点发送给其他用户的userId
userId: loginUserId,
data: text
}
ws.send(JSON.stringify(data));
消息体msg对象自己按需定义即可,至此基于JavaEE的websocket全部实现;如果要对登录的session进行处理,我们可以通过ServletRequestListener 封装httpsseion实现HttpSessionConfigurator的方法;
package com.test.web.websocket;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
@WebListener
public class RequestListener implements ServletRequestListener {
@Override
public void requestInitialized(ServletRequestEvent sre) {
//将所有request请求都携带上httpSession
((HttpServletRequest) sre.getServletRequest()).getSession();
}
public RequestListener() {
// TODO Auto-generated constructor stub
}
@Override
public void requestDestroyed(ServletRequestEvent arg0) {
// TODO Auto-generated method stub
}
}
实现HttpSessionConfigurator;
package com.hikvision.web.websocket;
import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import javax.websocket.server.ServerEndpointConfig.Configurator;
/**
* @author
* @Description: 将http request的session 存入websocket的session内
* @date 2018年11月30日 15:30
*/
public
class HttpSessionConfigurator extends Configurator {
@Override
public void modifyHandshake(ServerEndpointConfig sec,
HandshakeRequest request, HandshakeResponse response) {
// 获取当前Http连接的session
HttpSession httpSession = (HttpSession) request.getHttpSession();
// 将http session信息注入websocket session
sec.getUserProperties().put(HttpSession.class.getName(), httpSession);
}
}
在服务端代码改写如下:
@ServerEndpoint(value = "/websocketServer/{loginUserId}", configurator = HttpSessionConfigurator.class)
操作session方法
@OnOpen
public void onOpen(Session session, EndpointConfig config){
// 获取httpSession
this.httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
// 获取session对象内容
String user = (String) this.httpSession.getAttribute("account");
....
}
以上是基于网友的借鉴和总结,有不足之处,希望大家批评指正,通过项目使用 ,方案可行;后面会写一篇是为兼容浏览器采用Spring+WebSocket+SocketJs的消息推送方案;