1.先是pom.xml添加依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2.application.properties不需要添加任何配置 ,我只設置了一下服務server.port=8008
3.開啓WebSocket支持
package com.pay.websocket;
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 {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
4.然後是關鍵,WebSocket的各個監聽方法:
package com.pay.websocket;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pay.api.common.MyLog;
import com.pay.entity.PayOrders;
import com.pay.service.PayOrdersService;
import com.pay.utils.TimeMillisUtil;
import com.pay.web.ReceiptController;
@ServerEndpoint("/websocket/{token}")
@Component
public class WebSocketServer {
private final MyLog _log = MyLog.getLog(ReceiptController.class);
// 靜態變量,用來記錄當前在線連接數。應該把它設計成線程安全的。
private static int onlineCount = 0;
// concurrent包的線程安全Set,用來存放每個客戶端對應的MyWebSocket對象。
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
// 與某個客戶端的連接會話,需要通過它來給客戶端發送數據
private Session session;
// 接收token
private String token = "";
/**
* 連接建立成功調用的方法
*/
@OnOpen
public void onOpen(Session session, @PathParam("token") String token) {
this.session = session;
webSocketSet.add(this); // 加入set中
addOnlineCount(); // 在線數加1
_log.info("有新窗口開始監聽token:" + token + ",當前在線人數爲" + getOnlineCount());
this.token = token;
try {
sendMessage("連接成功");
} catch (Exception e) {
_log.info("websocket IO異常");
}
}
/**
* 連接關閉調用的方法
*/
@OnClose
public void onClose() {
try {
webSocketSet.remove(this); // 從set中刪除
subOnlineCount(); // 在線數減1
_log.info("有一連接關閉!當前在線人數爲" + getOnlineCount());
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
/**
* 收到客戶端消息後調用的方法
*
* @param message 客戶端發送過來的消息
*/
// @OnMessage
public void onMessage(String message, Session session) {
_log.info("收到來自窗口" + token + "的信息:" + 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) {
//error.printStackTrace(); 打印異常日誌
}
/**
* 實現服務器主動推送
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 羣發自定義消息
*/
@OnMessage
public void sendInfo(String message, @PathParam("token") String token) throws IOException {
//message前端發送過來的參數-可以自定義返回消息給前端
for (WebSocketServer item : webSocketSet) {
try {
// 這裏可以設定只推送給這個sid的,爲null則全部推送
if (token == null) {
item.sendMessage(message);
} else if (item.token.equals(token)) {
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--;
}
}
6.到這裏,接下來用一個HTML5 頁面,連接當前的WebSocket節點,接/發消息:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>WebSocket</title>
<script>
var socket;
if(typeof(WebSocket) == "undefined") {
console.log("您的瀏覽器不支持WebSocket");
}else{
console.log("您的瀏覽器支持WebSocket");
//實現化WebSocket對象,指定要連接的服務器地址與端口 建立連接
//等同於
socket = new WebSocket("ws://localhost:8008/websocket/token");
//socket = new WebSocket("${basePath}websocket/${cid}".replace("http","ws"));
//打開事件
socket.onopen = function() {
console.log("Socket 已打開");
socket.send("{'scope': '0','scopes': '5000','page': 0,'size': 5}");
};
//獲得消息事件
socket.onmessage = function(msg) {
console.log(msg.data);
//發現消息進入 開始處理前端觸發邏輯
};
//關閉事件
socket.onclose = function() {
console.log("Socket已關閉");
};
//發生了錯誤事件
socket.onerror = function() {
alert("Socket發生了錯誤");
//此時可以嘗試刷新頁面
}
//離開頁面時,關閉socket
//jquery1.8中已經被廢棄,3.0中已經移除
// $(window).unload(function(){
// socket.close();
//});
}
</script>
</head>
<body>
</body>
</html>