- 添加依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
- 添加 MyWebSocket 类
package com.jfsoft.socket; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.websocket.*; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.util.LinkedHashMap; import java.util.Map; /** * @author ChenXc * @version V1.0 * @Date 2018/10/8 15:07 * @Description TODO(一句话描述类作用) */ @ServerEndpoint(value = "/websocket") //接受websocket请求路径 @Component //注册到spring容器中 public class MyWebSocket { //保存所有在线socket连接 private static Map, MyWebSocket> webSocketMap = new LinkedHashMap<>(); //记录当前在线数目 private static int count = 0; //当前连接(每个websocket连入都会创建一个MyWebSocket实例 private Session session; private Logger log = LoggerFactory.getLogger(this.getClass()); //处理连接建立 @OnOpen public void onOpen(Session session) { this.session = session; webSocketMap.put(session.getId(), this); addCount(); log.info("新的连接加入:{}", session.getId()); } //接受消息 @OnMessage public void onMessage(String message, Session session) { log.info("收到客户端{}消息:{}", session.getId(), message); try { this.sendMessage("收到消息:" + message); } catch (Exception e) { e.printStackTrace(); } } //处理错误 @OnError public void onError(Throwable error, Session session) { log.info("发生错误{},{}", session.getId(), error.getMessage()); } //处理连接关闭 @OnClose public void onClose() { webSocketMap.remove(this.session.getId()); reduceCount(); log.info("连接关闭:{}", this.session.getId()); } //群发消息 //发送消息 public void sendMessage(String message) throws IOException { this.session.getBasicRemote().sendText(message); } //广播消息 public static void broadcast(String msg) { MyWebSocket.webSocketMap.forEach((k, v) -> { try { v.sendMessage(msg); } catch (Exception e) { } }); } //获取在线连接数目 public static int getCount() { return count; } //操作count,使用synchronized确保线程安全 public static synchronized void addCount() { MyWebSocket.count++; } public static synchronized void reduceCount() { MyWebSocket.count--; } }
- 添加 WebSocketConfig 类
package com.jfsoft.socket; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; /** * @author ChenXc * @version V1.0 * @Date 2018/10/8 15:06 * @Description TODO(一句话描述类作用) */ @Configuration public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter(){ return new ServerEndpointExporter(); } }
- 添加测试页面 test.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>websocket测试</h1> </body> <script> let socket = new WebSocket("ws://localhost:8080/websocket"); socket.onerror = err => { console.log(err); }; socket.onopen = event => { console.log(event); }; socket.onmessage = msg => { console.log(msg) }; socket.onclose = () => { console.log("连接关闭"); }; function sendMessage() { if (socket.readyState === 1) socket.send("这是一个测试数据"); else alert("尚未建立websocket连接"); } </script> </html>
注意:springboot 下 websocket 运行没问题,但是打包会报错,解决如下
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于