一、前端页面
- html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>webSockettitle>
- <style type="text/css">
- style>
- head>
- <body>
- <h1>WebSocketh1>
- <input type="button" onclick="websocket.send('666666666')" value="点我发消息"/>
- body>
- <script type="application/javascript">
- var websocket = {
- send: function (str) {
- }
- };
- window.onload = function () {
- if (!'WebSocket' in window) return;
- webSocketInit();
- };
- function webSocketInit() {
- websocket = new WebSocket("ws://localhost:8081//websocket/socket");
- //成功建立连接
- websocket.onopen = function () {
- websocket.send("成功连接到服务器");
- };
- //接收到消息
- websocket.onmessage = function (event) {
- console.log(event.data)
- };
- //连接发生错误
- websocket.onerror = function () {
- alert("WebSocket连接发生错误");
- };
- //连接关闭
- websocket.onclose = function () {
- alert("WebSocket连接关闭");
- };
- //监听窗口关闭事件,当窗口关闭时,主动关闭websocket连接
- window.onbeforeunload = function () {
- websocket.close()
- };
- }
- script>
- html>
二、后端代码
2.1 maven引入
-
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-websocketartifactId>
- dependency>
2.2 配置类
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.web.socket.config.annotation.EnableWebSocket;
- import org.springframework.web.socket.server.standard.ServerEndpointExporter;
-
- @Configuration
- @EnableWebSocket
- public class WebSocketConfig {
-
- @Bean
- public ServerEndpointExporter serverEndpointExporter() {
- return new ServerEndpointExporter();
- }
-
- }
2.3 接收实现类
- import org.springframework.stereotype.Component;
-
- import javax.websocket.*;
- import javax.websocket.server.ServerEndpoint;
- import java.io.IOException;
- import java.util.concurrent.CopyOnWriteArraySet;
-
- @Component
- @ServerEndpoint("/websocket/socket") //暴露的ws应用的路径
- public class WebSocket {
- //concurrent包下线程安全的Set
- private static final CopyOnWriteArraySet
SESSIONS = new CopyOnWriteArraySet<>(); - private Session session;
-
- @OnOpen
- public void onOpen(Session session) {
- this.session = session;
- SESSIONS.add(this);
- System.out.println(String.format("成功建立连接~ 当前总连接数为:%s", SESSIONS.size()));
- System.out.println(this);
- }
-
- @OnClose
- public void onClose() {
- SESSIONS.remove(this);
- System.out.println(String.format("成功关闭连接~ 当前总连接数为:%s", SESSIONS.size()));
- }
-
- @OnMessage
- public void onMessage(String message, Session session) {
- System.out.println(message);
- }
-
- @OnError
- public void onError(Session session, Throwable error) {
- System.out.println("发生错误");
- error.printStackTrace();
- }
-
- /**
- * 指定发消息
- *
- * @param message
- */
- public void sendMessage(String message) {
- try {
- this.session.getBasicRemote().sendText(message);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- /**
- * 群发消息
- *
- * @param message
- */
- public static void fanoutMessage(String message) {
- SESSIONS.forEach(ws -> ws.sendMessage(message));
- }
- }