创建配置类 WebSocketConfig?
package com.lockan.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* @author zhangjx
* @date 2021-08-26
*/
@Configuration
public class WebSocketConfig {
/**
* 注入一个ServerEndpointExporter,该Bean会自动注册使用@ServerEndpoint注解申明的websocket endpoint
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
创建工具类?WebSocketServer
package com.lockan.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author zhangjx
* @date 2021/08/26
*/
@Component
@ServerEndpoint("/webSocket/info/{userId}")
public class WebSocketServer {
private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketServer.class);
/**
* 心跳消息标记
*/
private static final String HEART_BEAT_FLAG = "heartbeat";
/**
* 统计在线人数
*/
private static final AtomicInteger ONLINE_NUM = new AtomicInteger();
/**
* 记录每个客户的session
*/
private static final ConcurrentHashMap<String, Session> SESSION_POOLS = new ConcurrentHashMap<>();
/**
* 建立连接成功调用
*
* @param session 会话session
* @param userId userId
*/
@OnOpen
public void onOpen(Session session, @PathParam(value = "userId") String userId) {
SESSION_POOLS.put(userId, session);
ONLINE_NUM.incrementAndGet();
LOGGER.info("{}加入webSocket!当前人数为:{}", userId, ONLINE_NUM);
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose(Session session, @PathParam(value = "userId") String userId) {
SESSION_POOLS.remove(userId);
ONLINE_NUM.decrementAndGet();
LOGGER.info("有一连接关闭!userId={},====当前剩余连接的webSocket为:{}", userId, ONLINE_NUM);
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
* @param session 可选的参数
*/
@OnMessage
public void onMessage(String message, Session session) throws IOException {
if (HEART_BEAT_FLAG.equals(message)) {
sendMessage(HEART_BEAT_FLAG, session);
LOGGER.info("心跳消息");
}
LOGGER.info(message);
}
/**
* 发送消息
*
* @param message 消息类容
* @param session 会话session
* @throws IOException io异常
*/
private void sendMessage(String message, Session session) throws IOException {
session.getBasicRemote().sendText(message);
LOGGER.info("消息发送成功,message:{}", message);
}
}
WebSocket测试页
<!DOCTYPE HTML>
<html>
<head>
<title>My WebSocket</title>
</head>
<body>
<input id="text" type="text" />
<button onclick="send()">Send</button>
<button onclick="closeWebSocket()">Close</button>
<div id="message"></div>
</body>
<script type="text/javascript">
var websocket = null;
//判断当前浏览器是否支持WebSocket, 主要此处要更换为自己的地址
if ('WebSocket' in window) {
websocket = new WebSocket("ws://ip地址:端口号/webSocket/info/662");
} else {
alert('Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function() {
setMessageInnerHTML("error");
};
//连接成功建立的回调方法
websocket.onopen = function(event) {
//setMessageInnerHTML("open");
}
//接收到消息的回调方法
websocket.onmessage = function(event) {
setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function() {
setMessageInnerHTML("close");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function() {
websocket.close();
}
//将消息显示在网页上
function setMessageInnerHTML(innerHTML) {
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
//关闭连接
function closeWebSocket() {
websocket.close();
}
//发送消息
function send() {
var message = document.getElementById('text').value;
websocket.send(message);
}
</script>
</html>
|