一、Websocket简介
随着互联网的发展,传统的HTTP协议已经很难满足Web应用日益复杂的需求了。近年来,随着HTML5的诞生,WebSocket协议被提出,它实现了浏览器与服务器的全双工通信,扩展了浏览器与服务端的通信功能,使服务端也能主动向客户端发送数据。
我们知道,传统的HTTP协议是无状态的,每次请求(request)都要由客户端(如 浏览器)主动发起,服务端进行处理后返回response结果,而服务端很难主动向客户端发送数据;这种客户端是主动方,服务端是被动方的传统Web模式 对于信息变化不频繁的Web应用来说造成的麻烦较小,而对于涉及实时信息的Web应用却带来了很大的不便,如带有即时通信、实时数据、订阅推送等功能的应 用。在WebSocket规范提出之前,开发人员若要实现这些实时性较强的功能,经常会使用折衷的解决方法:轮询(polling)和Comet技术。其实后者本质上也是一种轮询,只不过有所改进。
轮询是最原始的实现实时Web应用的解决方案。轮询技术要求客户端以设定的时间间隔周期性地向服务端发送请求,频繁地查询是否有新的数据改动。明显地,这种方法会导致过多不必要的请求,浪费流量和服务器资源。
Comet技术又可以分为长轮询和流技术。长轮询改进了上述的轮询技术,减小了无用的请求。它会为某些数据设定过期时间,当数据过期后才会向服务端发送请求;这种机制适合数据的改动不是特别频繁的情况。流技术通常是指客户端使用一个隐藏的窗口与服务端建立一个HTTP长连接,服务端会不断更新连接状态以保持HTTP长连接存活;这样的话,服务端就可以通过这条长连接主动将数据发送给客户端;流技术在大并发环境下,可能会考验到服务端的性能。
这两种技术都是基于请求-应答模式,都不算是真正意义上的实时技术;它们的每一次请求、应答,都浪费了一定流量在相同的头部信息上,并且开发复杂度也较大。
伴随着HTML5推出的WebSocket,真正实现了Web的实时通信,使B/S模式具备了C/S模式的实时通信能力。WebSocket的工作流程是这 样的:浏览器通过JavaScript向服务端发出建立WebSocket连接的请求,在WebSocket连接建立成功后,客户端和服务端就可以通过 TCP连接传输数据。因为WebSocket连接本质上是TCP连接,不需要每次传输都带上重复的头部数据,所以它的数据传输量比轮询和Comet技术小 了很多。本文不详细地介绍WebSocket规范,主要介绍下WebSocket在Java Web中的实现。
二、Websocket实战
1、Gradle引入websocket依赖
2、继承TextWebSocketHandler
package com.zajl.system.common.utils.websocket;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.io.IOException;
import java.net.URI;
import java.util.*;
public class WebSocketHandler extends TextWebSocketHandler {
private static final Logger LOGGER = LogManager.getLogger("WebSocketHandler");
//在线用户列表
private static final Map<String, WebSocketSession> users;
static {
users = new HashMap<>();
}
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
URI uri = session.getUri();
if (Objects.isNull(uri) || StringUtils.isEmpty(uri)){
return;
}
users.put(getUserId(session), session);
LOGGER.info("成功建立连接");
}
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) {
String msg = message.getPayload();
if ("ping".equals(msg)){
sendToUser(new TextMessage("pong"), Arrays.asList(getUserId(session)));
return;
}
}
/**
* 发送信息给指定用户
* @param userIds
* @param message
* @return
*/
public boolean sendToUser(TextMessage message, List<String> userIds) {
if (CollectionUtils.isEmpty(userIds)){
return false;
}
try {
for(String userId: userIds){
if (Objects.nonNull(users.get(userId))) {
users.get(userId).sendMessage(message);
} else {
LOGGER.info("当前用户不在线");
}
}
}catch (IOException e){
//e.printStackTrace();
}
return true;
}
/**
* 广播信息
* @param message
*/
public void sendToAllUser(TextMessage message){
try {
for (String key : users.keySet()) {
users.get(key).sendMessage(message);
}
}catch (IOException e){
//e.printStackTrace();
}
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
if (session.isOpen()) {
session.close();
}
LOGGER.info("连接出错");
users.remove(getUserId(session));
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
LOGGER.info("连接已关闭:" + status);
users.remove(getUserId(session));
}
@Override
public boolean supportsPartialMessages() {
return false;
}
private String getUserId(WebSocketSession session){
URI uri = session.getUri();
if (Objects.isNull(uri) || StringUtils.isEmpty(uri)){
return "";
}
return uri.getPath().substring(uri.getPath().lastIndexOf("/") + 1, uri.getPath().length());
}
}
3、实现WebSocketConfigurer定义websocket注册地址
package com.zajl.system.common.utils.websocket;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(myHandler(), "/websocket/*").setAllowedOrigins("*");
}
@Bean
public WebSocketHandler myHandler(){
return new WebSocketHandler();
}
}
4、创建发送消息工具类
package com.zajl.system.common.utils.websocket;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.TextMessage;
import java.util.Arrays;
import java.util.List;
public class WebSocketUtils {
private static final WebSocketHandler webSocketHandler = new WebSocketHandler();
/**
* 发送给指定单个用户
* @param msg 消息
* @param userId 用户id
*/
public static void sendMsgToSingleUser(String msg, String userId){
if (StringUtils.isEmpty(msg) || StringUtils.isEmpty(userId)){
return;
}
sendMsgToUsers(msg, Arrays.asList(userId));
}
/**
* 发送给指定某些用户
* @param msg 消息
* @param userIds 用户id集合
*/
public static void sendMsgToUsers(String msg, List<String> userIds){
if (StringUtils.isEmpty(msg) || CollectionUtils.isEmpty(userIds)){
return;
}
webSocketHandler.sendToUser(new TextMessage(msg), userIds);
}
/**
* 发送给所有用户
* @param msg
*/
public static void sendMsgToAllUser(String msg){
if (StringUtils.isEmpty(msg)){
return;
}
webSocketHandler.sendToAllUser(new TextMessage(msg));
}
}
5.js处理
var socket = null;
var lockReconnect = false; //避免ws重复连接
var isSupport = function () {
if (typeof(WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
return false;
} else {
console.log("您的浏览器支持WebSocket");
return true
}
}
var doConnect = function () {
if (!isSupport()) {
return;
}
var url = window.location.host;
var userId = $("#currentUserId").val();
if (!userId){
return;
}
if (window.location.protocol == 'http:') {
url = "ws://" + url + "/cms/websocket/" + userId;
} else {
url = "wss://" + url + "/cms/websocket/" + userId;
}
createWebSocket(url);
}
var createWebSocket = function (url) {
try {
if ('WebSocket' in window) {
socket = new WebSocket(url);
} else if ('MozWebSocket' in window) {
socket = new MozWebSocket(url);
} else {
}
initEventHandle(url);
} catch (e) {
reconnect(url);
console.log(e);
}
}
var initEventHandle = function (url) {
//打开事件
socket.onopen = function () {
heartCheck.reset().start(); //心跳检测重置
console.log("Socket 已打开");
};
//获得消息事件
socket.onmessage = function (msg) {
heartCheck.reset().start(); //拿到任何消息都说明当前连接是正常的
//发现消息进入
console.log(msg.data);
//心跳连接检查
if (msg.data == "pong") {
return;
}
showNotification(msg.data);
};
//关闭事件
socket.onclose = function () {
console.log("Socket已关闭");
reconnect(url);
};
//发生了错误事件
socket.onerror = function () {
console.log("Socket发生了错误");
reconnect(url);
}
// $(window).unload(function(){
// socket.close();
// });
}
// 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
socket.close();
};
var reconnect = function (url) {
if (lockReconnect) return;
lockReconnect = true;
setTimeout(function () { //没连接上会一直重连,设置延迟避免请求过多
createWebSocket(url);
lockReconnect = false;
}, 2000);
};
//心跳检测
var heartCheck = {
timeout: 50000, //50秒一次心跳
timeoutObj: null,
serverTimeoutObj: null,
reset: function () {
clearTimeout(this.timeoutObj);
clearTimeout(this.serverTimeoutObj);
return this;
},
start: function () {
var self = this;
this.timeoutObj = setTimeout(function () {
//这里发送一个心跳,后端收到后,返回一个心跳消息,
//onmessage拿到返回的心跳就说明连接正常
socket.send("ping");
console.log("ping!")
self.serverTimeoutObj = setTimeout(function () {//如果超过一定时间还没重置,说明后端主动断开了
socket.close(); //如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
}, self.timeout)
}, this.timeout)
}
};
var showNotification = function (msg) {
//后台推送的消息
if (!msg){
return;
}
// toastr.options = {
// "closeButton": true,
// "debug": false,
// "positionClass": "toast-bottom-right",
// "showDuration": "1000",
// "hideDuration": "1000",
// "timeOut": "0",
// "extendedTimeOut ": "0",
// "showEasing": "swing",
// "hideEasing": "linear",
// "showMethod": "fadeIn",
// "hideMethod": "fadeOut"
// };
//
//
//
// toastr.options.onclick = function () {
// //TODO 点击连接弹出框跳转
// };
// toastr['success'](msg, "消息提醒");
window.location.reload()
};
doConnect();
6、运行效果
待办列表点击进去审核详情页-->审核通过后待办列表实时刷新