做個SpringBoot Socket使用的簡單記錄
功能:后臺實時向前臺發(fā)送提醒信息
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.2.3</version>
<classifier>jdk15</classifier><!-- jdk版本 -->
</dependency>
</dependencies>
@Component
@ServerEndpoint("/msg/{userID}")
public class MsgSocket {
private static final Logger logger = LoggerFactory.getLogger(MsgSocket.class);
private static Map<String, Session> clients = new ConcurrentHashMap<>();
@OnOpen
public void open(@PathParam("userID")String userID,Session session) {
clients.put(userID, session);
logger.info("userID:{},session:{}",userID,session.getAsyncRemote());
}
@OnMessage
public void onMessage(String message) throws IOException {
JSONObject jsonTo = JSONObject.fromObject(message);
String msg = (String) jsonTo.get("message");
String userID = (String) jsonTo.get("userID");
sendMessageTo(msg,userID);
}
private void sendMessageTo(String message, String userID) throws IOException {
Session session = clients.get(userID);
if (session == null) {
return;
}
session.getAsyncRemote().sendText(message);
}
@OnError
public void onError(Session session, Throwable error) {
error.printStackTrace();
}
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
@RestController
public class TestController {
@GetMapping("/test")
public String test() throws IOException {
MsgSocket msgSocket = new MsgSocket();
JSONObject jo = new JSONObject();
jo.put("message", "這是后臺返回的消息浙宜!");
jo.put("userID","huang");
msgSocket.onMessage(jo.toString());
return "success";
}
}
用一個簡單頁面做測試
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<script>
var websocket = null;
var host = document.location.host;
var username = "huang"; // 獲得當前登錄人員的userName
// alert(username)
//判斷當前瀏覽器是否支持WebSocket
if ('WebSocket' in window) {
alert("瀏覽器支持Websocket"+host)
websocket = new WebSocket('ws://' + 'localhost:8080' + '/msg/' + username);
alert('ws://' + 'localhost:8080' + '/msg/' + username)
} else {
alert('當前瀏覽器 Not support websocket')
}
//連接發(fā)生錯誤的回調(diào)方法
websocket.onerror = function (e) {
alert(e)
alert("WebSocket連接發(fā)生錯誤")
setMessageInnerHTML("WebSocket連接發(fā)生錯誤");
};
//連接成功建立的回調(diào)方法
websocket.onopen = function () {
alert("WebSocket連接成功")
setMessageInnerHTML("WebSocket連接成功");
}
//接收到消息的回調(diào)方法
websocket.onmessage = function (event) {
alert("接收到消息的回調(diào)方法")
alert("這是后臺推送的消息:" + event.data);
websocket.close();
alert("webSocket已關(guān)閉溉仑!")
}
//連接關(guān)閉的回調(diào)方法
websocket.onclose = function () {
setMessageInnerHTML("WebSocket連接關(guān)閉");
}
//監(jiān)聽窗口關(guān)閉事件,當窗口關(guān)閉時益楼,主動去關(guān)閉websocket連接沸毁,防止連接還沒斷開就關(guān)閉窗口训貌,server端會拋異常。
window.onbeforeunload = function () {
closeWebSocket();
}
//關(guān)閉WebSocket連接
function closeWebSocket() {
websocket.close();
}
//將消息顯示在網(wǎng)頁上
function setMessageInnerHTML(innerHTML) {
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
</script>
<body>
</body>
</html>