1.引入依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency>
2.前端代码
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body><h1>12</h1>
<script>var websocket = null;if ('WebSocket' in window){websocket = new WebSocket('ws://localhost:8080/webSocket');}else {alert("不支持websocket ")}websocket.onopen = function (event){console.log('建立连接')}websocket.onclose = function (event){console.log('连接关闭')}websocket.onmessage = function (event){console.log('收到消息'+event.data)}websocket.onerror = function (){alert('错误')}window.onbeforeunload = function (){websocket.close();}
</script>
</body>
</html>
3.后端代码
@Component
public class WebConfig {@Beanpublic ServerEndpointExporter serverEndpointExporter(){return new ServerEndpointExporter();}
}@Component
@ServerEndpoint("/webSocket")
public class WebSocket {private Session session;private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();@OnOpenpublic void onOpen(Session session){this.session = session;webSockets.add(this);System.out.println("webSocket消息,有新的连接 总数" + webSockets.size());}@OnClosepublic void onClose(){this.session = session;webSockets.remove(this);System.out.println("webSocket消息,连接断开 总数" + webSockets.size());}@OnMessagepublic void onMessage(String message){System.out.println("客户端消息" + message);}public void sendMessage(String message){for (WebSocket webSocket : webSockets) {System.out.println("广播消息" + message);try {webSocket.session.getBasicRemote().sendText(message);} catch (IOException e) {e.printStackTrace();}}}
}