第一:引入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;
第五:運行效果
有心跳監聽,無心跳監聽結果大家就自己試哈


