- 引入pom文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.0.4.RELEASE</version>
</dependency>
2.配置webSocket
/**
* @Description 开启WebSocket支持
* @ClassName WebSocketConfig
* @Author kevin
* @Date 2019/7/11 10:14
* @Version 1.0
**/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
- 定义webSocket的服务端
/**
* @Description TODO
* @ClassName WebSocket
* @Author kevin
* @Date 2019/7/11 10:14
* @Version 1.0
**/
@ServerEndpoint("/monitor/webSocket")
@Component
@Slf4j
public class WebSocket {
/**
* 全局链接数
*/
private static int onlineCount = 0;
/**
* 保存连接用户
*/
private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<WebSocket>();
private Session session;
/**
* 建立链接触发
*
* @param session
*/
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this);
addOnlineCount();
log.info("-----------websocket建立连接------当前链接数:{}---", JSONObject.toJSONString(getOnlineCount()));
}
/**
* 断开链接触发
*/
@OnClose
public void onClose() {
webSocketSet.remove(this);
subOnlineCount();
log.info("-----------websocket断开连接------当前链接数:{}---", JSONObject.toJSONString(getOnlineCount()));
}
/**
* 接收来自客户端的消息
*
* @param message 接收消息
* @param session
*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("-----------websocket收到来自客户端的消息:{}---------", message);
// 将收到的消息群发给所有在线
webSocketSet.forEach(item -> {
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
});
}
/**
* 发生错误时触发
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误");
error.printStackTrace();
}
/**
* 服务器主动推送
*
* @param message
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 群发自定义消息
*/
public void sendInfo(JSONObject message) throws IOException {
log.info("推送消息到推送内容:" + message);
webSocketSet.forEach(item -> {
try {
item.sendMessage(message.toJSONString());
} catch (IOException e) {
e.printStackTrace();
}
});
}
/**
* 移除链接
*/
public static synchronized void subOnlineCount() {
WebSocket.onlineCount--;
}
/**
* 获取链接数
*
* @return
*/
public static synchronized int getOnlineCount() {
return WebSocket.onlineCount;
}
/**
* 添加链接数
*/
public static synchronized void addOnlineCount() {
WebSocket.onlineCount++;
}
}
- 前端和后端建立链接(本地测试请下载jquery-3.4.1.min.js、sockjs.js、stomp.min.js三个JS)
<!DOCTYPE HTML>
<html>
<head>
<title>kevin WebSocket Test</title>
</head>
<body>
Welcome<br/>
<input id="text" type="text" /><button οnclick="send()">Send</button> <button οnclick="closeWebSocket()">Close</button>
<div id="message">
</div>
</body>
<script type="text/javascript">
var websocket = null;
//判断当前浏览器是否支持WebSocket
if('WebSocket' in window){
// 与服务端创建的连接
websocket = new WebSocket("ws://localhost:8880/monitor/webSocket");
}
else{
// 浏览器不支持webSocket时使用SockJS
websocket = new SockJS("http://127.0.0.1:8080/my/socket");
// 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>