Springboot集成Websocket,前端监听⼼跳实现第⼀:引⼊jar
由于项⽬是springboot的项⽬所以我这边简单的应⽤了springboot⾃带的socket jar
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
第⼆:Socket代码编写
import t.annotation.Bean;
import t.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 urrent.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;
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) {
<("websocket IO异常");
}
}
/**
* 连接关闭调⽤的⽅法
*/
@OnClose
public void onClose() {
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("⾮正常关闭,发⽣错误!====>" + String() + "当前在线⼈数为" + getOnlineCount());
}
public void sendMessage(String message) throws IOException {
BasicRemote().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() {
}
public static synchronized void subOnlineCount() {
}
}
发送消息调⽤
try {
WebSocketServer.sendInfo("⾃定义需要推送的消息" ,"111");
} catch (IOException e) {
e.printStackTrace();
}
上述代码在发送消息时,可以⽀持⼀条消息对应多个窗⼝
如果想要使⽤⼀个消息值推送到⼀个窗⼝,就使⽤⼀下springboot的管理
具体实现:
添加⼀个管理的类
import javax.websocket.server.ServerEndpointConfig;
import org.springframework.beans.BeansException;
import t.ApplicationContext;
import t.ApplicationContextAware;
public class MySpringConfigurator extends ServerEndpointConfig.Configurator implements ApplicationContextAware { private static volatile ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
}
@Override
public <T> T getEndpointInstance(Class<T> clazz) throws InstantiationException {
Bean(clazz);
}
}
import t.annotation.Bean;
import t.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 = place("https","wss");
}else{
wsUrl = place("http","ws");
}
console.log("socket 通讯地址:" + wsUrl);
ws = new WebSocket(wsUrl);
// 初始化链接
init();
} catch(e) {
console.log('catch'+e);
reconnect(wsUrl);
}
}
/**
* 初始化链接
*/
function init() {
console.log(getNowTime() +" Socket已关闭");
reconnect(wsUrl);
};
console.log(getNowTime() +' 发⽣异常了');
reconnect(wsUrl);
};
console.log(getNowTime() +" Socket 已打开");
ws.send("连接成功");
//⼼跳检测重置
heartCheck.start();
};
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 = place("https","wss");
}else{
wsUrl = place("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() {
console.log(getNowTime() +" Socket已关闭");
reconnect(wsUrl);
};
console.log(getNowTime() +' 发⽣异常了');
reconnect(wsUrl);
};
console.log(getNowTime() +" Socket 已打开");
ws.send("连接成功");
//⼼跳检测重置
heartCheck.start();
};
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);
//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 = FullYear();
nginx部署前端项目//获取当前⽉
var month = Month() + 1;
/
/获取当前⽇
var date = Date();
var h = Hours(); //获取当前⼩时数(0-23)
var m = Minutes(); //获取当前分钟数(0-59)
var s = Seconds();
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;
第五:运⾏效果
有⼼跳监听,⽆⼼跳监听结果⼤家就⾃⼰试哈
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论