Spring boot集成Websocket,前端监听心跳实现
第一:引入jar
由于项目是springboot的项目所以我这边简单的应用了springboot自带的socket jar
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
第二:Socket代码编写

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter; /**
* 开启WebSocket支持
*/
@Configuration
public class WebSocketConfig { /**
* 注入对象ServerEndpointExporter,这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
* @return
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
} }


import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet; import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint; import org.springframework.stereotype.Component; import lombok.extern.slf4j.Slf4j;
/**
* 发送消息的类
*/
@Slf4j
@Component
@ServerEndpoint(value = "/websocket/{sid}")
public class WebSocketServer { //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>(); //与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session; //接收sid
private String sid="";
/**
* 连接建立成功调用的方法*/
@OnOpen
public void onOpen(Session session,@PathParam("sid") String sid) {
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在线数加1
log.info("有新窗口开始监听:"+sid+",当前在线人数为" + getOnlineCount());
this.sid=sid;
try {
sendMessage("连接成功");
} catch (IOException e) {
log.error("websocket IO异常");
}
} /**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //从set中删除
subOnlineCount(); //在线数减1
log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
} /**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("收到来自窗口"+sid+"的信息:"+message);
//群发消息
for (WebSocketServer item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
} /**
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.info("非正常关闭,发生错误!====>" + error.toString() + "当前在线人数为" + getOnlineCount());
}
/**
* 实现服务器主动推送
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
} /**
* 群发自定义消息
* */
public static void sendInfo(String message,@PathParam("sid") String sid) throws IOException {
log.info("推送消息到窗口"+sid+",推送内容:"+message);
for (WebSocketServer item : webSocketSet) {
try {
//这里可以设定只推送给这个sid的,为null则全部推送
if(sid==null) {
item.sendMessage(message);
}else if(item.sid.equals(sid)){
item.sendMessage(message);
}
} catch (IOException e) {
continue;
}
}
} public static synchronized int getOnlineCount() {
return onlineCount;
} public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
} public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}


发送消息调用
try {
WebSocketServer.sendInfo("自定义需要推送的消息" ,"111");
} catch (IOException e) {
e.printStackTrace();
}

上述代码在发送消息时,可以支持一条消息对应多个窗口
如果想要使用一个消息值推送到一个窗口,就使用一下springboot的管理
具体实现:
添加一个管理的类

import javax.websocket.server.ServerEndpointConfig; import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware; public class MySpringConfigurator extends ServerEndpointConfig.Configurator implements ApplicationContextAware {
private static volatile ApplicationContext context; @Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
MySpringConfigurator.context=applicationContext;
} @Override
public <T> T getEndpointInstance(Class<T> clazz) throws InstantiationException {
return context.getBean(clazz);
}
}


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter; /**
* 开启WebSocket支持
* @author zhengkai
*/
@Configuration
public class WebSocketConfig { /**
* 注入对象ServerEndpointExporter,这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
* @return
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
} @Bean
public MySpringConfigurator getSpringConfigurator(){
return new MySpringConfigurator();
}
}

加上这个对象多个窗口就只能一个窗口收到消息
第三步:前端配置
不带监听

var socket;
if(typeof(WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
}else{
console.log("您的浏览器支持WebSocket");
//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
//等同于socket = new WebSocket("ws://localhost:8083/checkcentersys/websocket/20");
var wsUrl = $("#url").val();
console.log("socket 链接地址:" + wsUrl);
if (wsUrl.indexOf("https") >= 0 ) {//如果是https webSocket 需要遵守wss协议所以这里判断如果是https socket
wsUrl = wsUrl.replace("https","wss");
}else{
wsUrl = wsUrl.replace("http","ws");
}
console.log("socket 通讯地址:" + wsUrl);
//创建链接
function createWebSocket() {
try {
ws = new WebSocket(wsUrl);
// 初始化链接
init();
} catch(e) {
console.log('catch'+e);
reconnect(wsUrl);
}
} /**
* 初始化链接
*/
function init() {
ws.onclose = function () {
console.log(getNowTime() +" Socket已关闭");
reconnect(wsUrl);
};
ws.onerror = function() {
console.log(getNowTime() +' 发生异常了');
reconnect(wsUrl);
};
ws.onopen = function () {
console.log(getNowTime() +" Socket 已打开");
ws.send("连接成功");
//心跳检测重置
heartCheck.start();
};
ws.onmessage = function (event) {
console.log(getNowTime() +' 接收到消息:'+event.data);
heartCheck.start();
//拿到任何消息都说明当前连接是正常的
//实时添加消息
}
}

带心跳监听

var socket;
if(typeof(WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
}else{
console.log("您的浏览器支持WebSocket");
//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
//等同于socket = new WebSocket("ws://localhost:8083/checkcentersys/websocket/20");
var wsUrl = $("#url").val();
console.log("socket 链接地址:" + wsUrl);
if (wsUrl.indexOf("https") >= 0 ) {//如果是https webSocket 需要遵守wss协议所以这里判断如果是https socket
wsUrl = wsUrl.replace("https","wss");
}else{
wsUrl = wsUrl.replace("http","ws");
}
console.log("socket 通讯地址:" + wsUrl);
var lockReconnect = false;//避免重复连接
var ws;
var tt;
//创建链接
createWebSocket();
//创建链接
function createWebSocket() {
try {
ws = new WebSocket(wsUrl);
// 初始化链接
init();
} catch(e) {
console.log('catch'+e);
reconnect(wsUrl);
}
} /**
* 初始化链接
*/
function init() {
ws.onclose = function () {
console.log(getNowTime() +" Socket已关闭");
reconnect(wsUrl);
};
ws.onerror = function() {
console.log(getNowTime() +' 发生异常了');
reconnect(wsUrl);
};
ws.onopen = function () {
console.log(getNowTime() +" Socket 已打开");
ws.send("连接成功");
//心跳检测重置
heartCheck.start();
};
ws.onmessage = function (event) {
console.log(getNowTime() +' 接收到消息:'+event.data);
heartCheck.start();
//拿到任何消息都说明当前连接是正常的
//实时添加消息
}
} var lockReconnect = false;//避免重复连接
//重试连接socket
function reconnect(wsUrl) {
if(lockReconnect) {
return;
};
lockReconnect = true;
//没连接上会一直重连,设置延迟避免请求过多
tt && clearTimeout(tt);
tt = setTimeout(function () {
createWebSocket(wsUrl);
lockReconnect = false;
}, 180000);
}
//心跳检测
var heartCheck = {
timeout: 210000,
timeoutObj: null,
serverTimeoutObj: null,
start: function(){
console.log(getNowTime() +" Socket 心跳检测");
var self = this;
this.timeoutObj && clearTimeout(this.timeoutObj);
this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
this.timeoutObj = setTimeout(function(){
//这里发送一个心跳,后端收到后,返回一个心跳消息,
//onmessage拿到返回的心跳就说明连接正常
console.log(getNowTime() +' Socket 连接重试');
ws.send("连接成功");
self.serverTimeoutObj = setTimeout(function() {
console.log(ws);
ws.close();
}, self.timeout);
}, this.timeout)
}
}
} /**
* 获取系统当前时间
* @returns
*/
function p(s) {
return s < 10 ? '0' + s : s;
}
function getNowTime() {
var myDate = new Date();
//获取当前年
var year = myDate.getFullYear();
//获取当前月
var month = myDate.getMonth() + 1;
//获取当前日
var date = myDate.getDate();
var h = myDate.getHours(); //获取当前小时数(0-23)
var m = myDate.getMinutes(); //获取当前分钟数(0-59)
var s = myDate.getSeconds();
return year + '-' + p(month) + "-" + p(date) + " " + p(h) + ':' + p(m) + ":" + p(s);
}

第四:nginx配置
https的服务。socket通讯的时候一般情况我们部署的项目设置有超时时间,所以会导致socket连接会关闭,因此我这边使用前端做了心跳监控,定时发送消息给后端,避免我的socket连接断开,导致前端不能接收到手段推送的消息
具体配置如下:
proxy_set_header Upgrade $http_upgrade; #支持wss
proxy_set_header Connection "upgrade"; #支持wss
proxy_redirect off;
proxy_connect_timeout 240;
proxy_send_timeout 240;
第五:运行效果
有心跳监听,无心跳监听结果大家就自己试哈


Spring boot集成Websocket,前端监听心跳实现的更多相关文章
- spring boot 集成 websocket 实现消息主动推送
spring boot 集成 websocket 实现消息主动 前言 http协议是无状态协议,每次请求都不知道前面发生了什么,而且只可以由浏览器端请求服务器端,而不能由服务器去主动通知浏览器端,是单 ...
- Spring Boot 集成 WebSocket 实现服务端推送消息到客户端
假设有这样一个场景:服务端的资源经常在更新,客户端需要尽量及时地了解到这些更新发生后展示给用户,如果是 HTTP 1.1,通常会开启 ajax 请求询问服务端是否有更新,通过定时器反复轮询服务端响应的 ...
- 【websocket】spring boot 集成 websocket 的四种方式
集成 websocket 的四种方案 1. 原生注解 pom.xml <dependency> <groupId>org.springframework.boot</gr ...
- spring boot集成Websocket
websocket实现后台像前端主动推送消息的模式,可以减去前端的请求获取数据的模式.而后台主动推送消息一般都是要求消息回馈比较及时,同时减少前端ajax轮询请求,减少资源开销. spring boo ...
- spring boot 集成 websocket 实现消息主动
来源:https://www.cnblogs.com/leigepython/p/11058902.html pom.xml 1 <?xml version="1.0" en ...
- spring boot集成websocket实现聊天功能和监控功能
本文参考了这位兄台的文章: https://blog.csdn.net/ffj0721/article/details/82630134 项目源码url: https://github.com/zhz ...
- Spring boot入门(二):Spring boot集成MySql,Mybatis和PageHelper插件
上一篇文章,写了如何搭建一个简单的Spring boot项目,本篇是接着上一篇文章写得:Spring boot入门:快速搭建Spring boot项目(一),主要是spring boot集成mybat ...
- Spring Boot系列教程十:Spring boot集成Sentinel Redis
前言 上一篇文章介绍了spring boot集成单点的redis,然而实际生产环境使用单点的redis风险很高,一旦宕机整个服务将无法使用,这篇文章介绍如何使用基于sentinel的redis高可用方 ...
- Spring boot集成RabbitMQ(山东数漫江湖)
RabbitMQ简介 RabbitMQ是一个在AMQP基础上完整的,可复用的企业消息系统 MQ全称为Message Queue, 消息队列(MQ)是一种应用程序对应用程序的通信方法.应用程序通过读写出 ...
随机推荐
- Javascript-基本使用
本章向您提供了展示 JavaScript 能力的部分实例. JavaScript 能够改变 HTML 内容 getElementById() 是多个 JavaScript HTML 方法之一. 本例使 ...
- Excel四象限散点图的制作方法
Excel中四象限散点图带文本数据标签,可以在散点图的基础上进行一些设置即可得到,无需第三方插件或者宏代码,非常方便,以office2013为例,效果如下: 步骤: 1.准备好数据源,选中两列数据源( ...
- 通过cmd命令控制台关闭已经打开的端口号
通过cmd命令控制台关闭已经打开的端口号 在出现的窗口里面输入 netstat -ano, 就会出现所有的端口号, Local Address下面的是端口号, PID就是某程序占用的进程号, 这个进程 ...
- win7蓝屏死机0x0000003B错误蓝屏故障解决
win7蓝屏死机0x0000003B错误蓝屏故障解决 刚才一个朋友问我:电脑蓝屏了怎么办. 我问他要了电脑的截图,自己看了错误代码:0x0000003B 搜索资料,查询了一番.都是说电脑中病毒或者是系 ...
- 了解一下JVM和GC工作机制
题外话:很久没有写博客了,事情颇多,今天空闲下来,学习一下顺便写一下自己的了解,机会总是留给有准备的人,所以平常一定要注意知识的巩固和积累.知识的深度也要有一定的理解,不比别人知道的多,公司干嘛选你? ...
- 在Jenkins的pipeline项目中运行jmeter测试-教程
Jenkins 2.0的发布引入了一种新的项目类型 - Pipeline,以前只能通过插件获得.从Jenkins 2.0开始,Pipeline项目开箱即用. 与通常的“自由式”项目相比,管道构建具有几 ...
- A Simple Question of Chemistry
#include<stdio.h> int main() { int i, l; ]; ]; l = ; ) { l++; } ; a[i]!= && i<l; i+ ...
- Matplotlib:绘图和可视化
Matplotlib:绘图和可视化 简介 简单绘制线形图 plot函数 支持图类型 保存图表 一 .简介 Matplotlib是一个强大的Python绘图和数据可视化的工具包.数据可视化也是我们数据分 ...
- 在Firefox中操作iframe的一个小问题
在做一个 Web 的打印功能时,需要将被打印的文档写到 iframe 的 document 中. <!doctype html> <html lang="en"& ...
- mysql_select 单表查询
select * *代表全部 查询多个字段 select 字段1,字段2,字段3 聚合函数 count(*) 统计 select count(*) ...