Spring boot实现WebSocket服务
1 引入jar
<!-- 整合 websocket-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2 编写组件
package com.lark.system.common.websocket.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; /*** * @ClassName: WebSocketConfig * @Description: WebSocket 配置 * @Auther: pengbaowei * @Date: 2019/12/12 * @version : V1.0 */ @Configuration public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } }
3 服务类
package com.lark.system.common.websocket.server; import org.springframework.stereotype.Component; import javax.websocket.*; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.util.concurrent.CopyOnWriteArraySet; /*** * @ClassName: WebSocketServer * @Description: WebSocket 服务 * @Auther: pengbaowei * @Date: 2019/12/12 * @version : V1.0 */ @ServerEndpoint("/webSocket/{sid}") @Component public class WebSocketServer { //在线数量 private static int onlineCount = 0; //concurrent包的线程安全Set,用来存放每个客户端对应的WebSocketServer对象。 private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>(); //与某个客户端的连接会话,需要通过它来给客户端发送数据 private Session session; //接收sid private String sid = ""; /** * 连接成功后事件 * @param session * @param sid */ @OnOpen public void onOpen(Session session, @PathParam("sid") String sid) { this.session = session; webSocketSet.add(this); addOnlineCount(); this.sid = sid; try { sendMessage("连接成功"); } catch (IOException e) { } } /** * 客户端关闭会事件 */ @OnClose public void onClose() { webSocketSet.remove(this); //从set中删除 subOnlineCount(); //在线数减1 } /** * 收到客户端的消息后事件 * @param message * @param session */ @OnMessage public void onMessage(String message, Session session) { try { session.getBasicRemote().sendText("服务端:系统已经收到你的消息!"); }catch (Exception e){ } } /** * 发生错误事件 * @param session * @param error */ @OnError public void onError(Session session, Throwable error) { //log.error("发生错误"); error.printStackTrace(); } /** * 实现服务器主动推送 */ public void sendMessage(String message) throws IOException { this.session.getBasicRemote().sendText(message); } /** * 群发自定义消息 */ public static void sendInfo(String message, @PathParam("sid") String sid) throws IOException { //log.info("推送消息到窗口"+sid+",推送内容:"+message); for (WebSocketServer item : webSocketSet) { try { //这里可以设定只推送给这个sid的,为null则全部推送 if (sid == null) { item.sendMessage(message); } else if (item.sid.equals(sid)) { item.sendMessage(message); } } catch (IOException e) { continue; } } } public static synchronized int getOnlineCount() { return onlineCount; } public static synchronized void addOnlineCount() { WebSocketServer.onlineCount++; } public static synchronized void subOnlineCount() { WebSocketServer.onlineCount--; } }
4 前端页面连接
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>客户端一</title> <script> var socketClient; if(typeof(WebSocket) == "undefined") { console.log("您的浏览器不支持WebSocket"); }else{ console.log("您的浏览器支持WebSocket"); //实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接 //等同于socket = new WebSocket("ws://127.0.0.1:8082/webSocket/1"); socketClient = new WebSocket("ws://127.0.0.1:8082/webSocket/1"); //打开事件 socketClient.onopen = function() { console.log("Socket 已打开"); socketClient.send("这是来自客户端的消息" + location.href + new Date()); }; //获得消息事件 socketClient.onmessage = function(msg) { console.log(msg.data); }; //关闭事件 socketClient.onclose = function() { console.log("Socket已关闭"); }; //发生了错误事件 socketClient.onerror = function() { alert("Socket发生了错误"); //此时可以尝试刷新页面 } //离开页面时,关闭socket //jquery1.8中已经被废弃,3.0中已经移除 // $(window).unload(function(){ // socket.close(); //}); } function sendMessage() { let msg = document.getElementById("msg").value; socketClient.send(msg); } </script> </head> <body> <div style="height: 500px; width: 60%" > <div style="height: 60%; width: 100%"> <input id="msg" type="text" style="width: 100%; height: 100%"> </div> <div><button onclick="sendMessage()">发送</button></div> </div> </body> </html>

浙公网安备 33010602011771号