package com.example.demo.websocket; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; /** * 开启WebSocket支持。 * * @author Da * @since 2019.6.18 */ @Configuration public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } } package com.example.demo.websocket; import java.io.IOException; import java.util.concurrent.CopyOnWriteArraySet; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import org.springframework.stereotype.Component; //import cn.hutool.log.Log;// 使用@Slf4j //import cn.hutool.log.LogFactory;// 使用@Slf4j import lombok.extern.slf4j.Slf4j; /** * @see <a>https://blog.csdn.net/moshowgame/article/details/80275084</a> * @see <a>http://www.ruanyifeng.com/blog/2017/05/websocket.html</a> * * 支持的浏览器: * @see <a>https://caniuse.com/#search=websockets<a/> */ @ServerEndpoint("/websocket/{sid}") @Component @Slf4j// 增长 public class WebSocketServer { // static Log log=LogFactory.get(WebSocketServer.class);// 使用@Slf4j //静态变量,用来记录当前在线链接数。应该把它设计成线程安全的。 private static int onlineCount = 0; //concurrent包的线程安全Set,用来存放每一个客户端对应的MyWebSocket对象。 private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>(); //与某个客户端的链接会话,须要经过它来给客户端发送数据 private Session session; //接收sid private String sid = ""; /** * 链接创建成功调用的方法 */ @OnOpen public void onOpen(Session session, @PathParam("sid") String sid) { this.session = session; webSocketSet.add(this); //加入set中 addOnlineCount(); //在线数加1 log.info("有新窗口开始监听:" + sid + ",当前在线人数为" + getOnlineCount()); this.sid = sid; try { sendMessage("链接成功"); } catch (IOException e) { log.error("websocket IO异常"); } } /** * 链接关闭调用的方法 */ @OnClose public void onClose() { webSocketSet.remove(this); //从set中删除 subOnlineCount(); //在线数减1 log.info("有一链接关闭!当前在线人数为" + getOnlineCount()); } /** * 收到客户端消息后调用的方法 * * @param message 客户端发送过来的消息 */ @OnMessage public void onMessage(String message, Session session) { log.info("收到来自窗口" + sid + "的信息:" + message); //群发消息 for (WebSocketServer item : webSocketSet) { 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(); } /** * 实现服务器主动推送 */ 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 || "all".equals(sid)) { 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--; } } package com.example.demo.websocket; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.io.IOException; @Controller @RequestMapping("/checkcenter") public class CheckCenterController { /** * 推送数据接口。 * * 样例: * 推送单个电视:http://localhost:8080/checkcenter/socket/push/20?message=notice * 推送所有电视:http://localhost:8080/checkcenter/socket/push/all?message=notice * * @param cid 客户端的id * @param message 推送的消息内容 * @return json字符串,包含客户端的id与消息内容或异常内容 */ @ResponseBody @RequestMapping("/socket/push/{cid}") public String pushToWeb(@PathVariable String cid, String message) { try { WebSocketServer.sendInfo(message, cid); } catch (IOException e) { e.printStackTrace(); return "{id:" + cid + ", error:" + e.getMessage() + "}"; } return "{id:" + cid + ", message:" + message + "}"; } }
<!-- 增长websocket 2019.6.18 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.8</version> <scope>provided</scope> </dependency>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Client</title> </head> <body> <script> /** * 能够直接打开本html,无需web服务器。 */ var socket; if(typeof(WebSocket) == "undefined") { console.log("您的浏览器不支持WebSocket"); }else{ console.log("您的浏览器支持WebSocket"); //实现化WebSocket对象,指定要链接的服务器地址与端口 创建链接 // 20表示该客户端的id,每一个客户端的id应该不一样 socket = new WebSocket("ws://localhost:8080/websocket/20"); //等同于 // socket = new WebSocket("http://localhost:8080/checkcenter/websocket/20").replace("http", "ws"); // socket = new WebSocket("${basePath}websocket/${cid}".replace("http","ws")); //打开事件 socket.onopen = function() { console.log("Socket 已打开"); //socket.send("这是来自客户端的消息" + location.href + new Date()); }; //得到消息事件 socket.onmessage = function(msg) { console.log(msg.data); //发现消息进入,开始处理前端触发逻辑 if (msg.data == "notice") { // 跳转到公告页面 window.location.href = "./notice.html"; } }; //关闭事件 socket.onclose = function() { console.log("Socket已关闭"); }; //发生了错误事件 socket.onerror = function() { alert("Socket发生了错误"); //此时能够尝试刷新页面 } //离开页面时,关闭socket //jquery1.8中已经被废弃,3.0中已经移除 // $(window).unload(function(){ // socket.close(); //}); } </script> </body> </html> socket = new WebSocket("ws://localhost:8080/websocket/22"); <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Notice</title> </head> <body> Notice. </body> </html>