springboot + websocket
1.引入pom依賴
-
<dependency>
-
<groupId>org.springframework.boot</groupId>
-
<artifactId>spring-boot-starter-websocket</artifactId>
-
</dependency>
2.新建websocket的服務
WebSocketServer.java
-
/**
-
* @Author: wyb
-
* @Date: 2018/7/12 20:04
-
* @Description:websoceket具體業務實現
-
*/
-
@ServerEndpoint(value = "/websocket")
-
@Component
-
public class WebSocketServer {
-
private final Logger logger = LoggerFactory.getLogger(this.getClass());
-
//靜態變數,用來記錄當前線上連線數。應該把它設計成執行緒安全的。
-
private static int onlineCount = 0;
-
//concurrent包的執行緒安全Set,用來存放每個客戶端對應的MyWebSocket物件。
-
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
-
//與某個客戶端的連線會話,需要通過它來給客戶端傳送資料
-
private Session session;
-
/**
-
* 連線建立成功呼叫的方法*/
-
@OnOpen
-
public void onOpen(Session session) {
-
this.session = session;
-
webSocketSet.add(this); //加入set中
-
addOnlineCount(); //線上數加1
-
}
-
/**
-
* 連線關閉呼叫的方法
-
*/
-
@OnClose
-
public void onClose() {
-
webSocketSet.remove(this); //從set中刪除
-
subOnlineCount(); //線上數減1
-
}
-
/**
-
* 收到客戶端訊息後呼叫的方法
-
*
-
* @param message 客戶端傳送過來的訊息*/
-
@OnMessage
-
public void onMessage(String message, Session session) {
-
System.out.println("來自客戶端的心跳:" + message);
-
}
-
/**
-
* 發生錯誤時呼叫
-
@OnError
-
**/
-
public void onError(Session session, Throwable error) {
-
if(error != null)
-
logger.error("WebSocketServer onError:" + error.getMessage());
-
}
-
/***
-
* 對單一客戶傳送推送訊息
-
* @param message 訊息內容
-
*/
-
public void sendMessage(String message){
-
try{
-
this.session.getBasicRemote().sendText(message);
-
}catch (Exception ex){
-
logger.error("WebSocketServer sendMessage:" + ex.getMessage());
-
}
-
}
-
/**
-
* 群發自定義訊息
-
* */
-
public static void broadcastSendInfo(String message){
-
try{
-
for (WebSocketServer item : webSocketSet) {
-
item.sendMessage(message);
-
}
-
}catch (Exception ex){
-
System.out.println(ex.getMessage());
-
}
-
}
-
public static synchronized void addOnlineCount() {
-
WebSocketServer.onlineCount++;
-
}
-
public static synchronized void subOnlineCount() {
-
WebSocketServer.onlineCount--;
-
}
-
}
3.向spring注入bean
-
@Bean
-
public ServerEndpointExporter serverEndpointExporter() {
-
return new ServerEndpointExporter();
-
}
4.新增websocket的js
MyWebSocket.js
-
/**
-
* Created by PC on 2018/2/11.
-
*/
-
var heartflag = true;
-
var webSocket = null;
-
var tryTime = 0;
-
$(function () {
-
initSocket();
-
});
-
/**
-
* 初始化websocket,建立連線
-
*/
-
function initSocket() {
-
if (!window.WebSocket) {
-
alert("您的瀏覽器不支援推送功能");
-
return false;
-
}
-
webSocket = null;
-
webSocket = new WebSocket("ws://" + window.location.host + "/websocket");
-
// 收到服務端訊息
-
webSocket.onmessage = function (msg) {
-
if(msg.data == "&"){
-
// 暫時不用伺服器反向傳送心跳
-
}else{
-
popmsg(msg.data);
-
}
-
};
-
// 異常
-
webSocket.onerror = function (event) {
-
heartflag = false;
-
};
-
// 建立連線
-
webSocket.onopen = function (event) {
-
heartflag = true;
-
heart();
-
tryTime = 0;
-
};
-
// 斷線重連
-
webSocket.onclose = function () {
-
heartflag = false;
-
tryTime++;
-
// 重試10次,每次之間間隔1秒
-
if (tryTime < 10) {
-
setTimeout(function () {
-
if(!heartflag){
-
webSocket = null;
-
initSocket();
-
//alert("第:" + tryTime + "次重新建鏈。");
-
}
-
}, 1000);
-
} else {
-
//alert("重連失敗.");
-
}
-
};
-
heartflag = true;
-
}
-
// 連線成功後傳送心跳
-
function heart() {
-
if (heartflag){
-
webSocket.send("&");
-
}
-
setTimeout("heart()", 10*1000);
-
}
-
function popmsg(popmsg){
-
//配置一個透明的詢問框
-
layer.msg('', {
-
time: 20000, //20s後自動關閉
-
offset: 'rb',
-
content: '<div style="padding: 20px 100px;">'+ popmsg +'</div>'
-
});
-
}
這裡顯示使用了layer的部分內容
請注意最好建立心跳,因為如果不建立心跳那麼網路中存在問題將有可能無法發現線路斷鏈。