<html> <head> <meta charset="UTF-8"> <title>websocket测试</title> <style type="text/css"> h3, h4 { text-align: center; } </style> </head> <body> <h1>前端的信息查看控制台</h1> <script type="text/javascript"> var socket; if (typeof (WebSocket) == "undefined") { console.log("遗憾:您的浏览器不支持WebSocket"); } else { console.log("恭喜:您的浏览器支持WebSocket"); socket = new WebSocket("ws://localhost:8089/ws/asset"); //连接打开事件 socket.onopen = function () { console.log("Socket 已打开"); socket.send("消息发送测试(From Client)"); }; //收到消息事件 socket.onmessage = function (msg) { console.log("接收到的消息", msg.data); }; //连接关闭事件 socket.onclose = function () { console.log("Socket已关闭"); }; //发生了错误事件 socket.onerror = function () { alert("Socket发生了错误"); }; //窗口关闭时,关闭连接 window.unload = function () { socket.close(); }; } </script> </body> </html>
package com.aiguigu.websocket.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; /** 如果是springBoot自带的嵌入式容器,则要开启 */ @Configuration public class WebGlobalConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } }
定义webSocket类
package com.aiguigu.websocket.config; 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.concurrent.CopyOnWriteArraySet; import java.util.concurrent.atomic.AtomicInteger; @ServerEndpoint(value = "/ws/asset") @Component public class MyWebSocket { private static Logger log = LoggerFactory.getLogger(MyWebSocket.class); /*自增操作*/ private static final AtomicInteger OnlineCount = new AtomicInteger(0); // concurrent包的线程安全Set,用来存放每个客户端对应的Session对象。 private static CopyOnWriteArraySet<Session> SessionSet = new CopyOnWriteArraySet<Session>(); /** * 连接建立成功调用的方法 */ @OnOpen public void onOpen(Session session) { System.out.println("建立连接"); SessionSet.add(session); // 在线数加1,并获取最后结果 int cnt = OnlineCount.incrementAndGet(); log.info("有连接加入,当前连接数为:{}", cnt); SendMessage(session, "连接成功xxxxx"); } /** * 连接关闭调用的方法 */ @OnClose public void onClose(Session session) { SessionSet.remove(session); int cnt = OnlineCount.decrementAndGet(); log.info("有连接关闭,当前连接数为:{}", cnt); } /** * 收到客户端消息后调用的方法 * * @param message 客户端发送过来的消息 */ @OnMessage public void onMessage(String message, Session session) { log.info("来自客户端的消息:{}", message); SendMessage(session, "服务器发来的内容:" + message); } /** * 出现错误 * * @param session * @param error */ @OnError public void onError(Session session, Throwable error) { log.error("发生错误:{},Session ID: {}", error.getMessage(), session.getId()); error.printStackTrace(); } /** * 发送消息,实践表明,每次浏览器刷新,session会发生变化。 * * @param session * @param message */ public static void SendMessage(Session session, String message) { try { session.getBasicRemote().sendText(String.format("%s (From Server,Session ID=%s)", message, session.getId())); } catch (IOException e) { log.error("发送消息出错:{}", e.getMessage()); e.printStackTrace(); } } /** * 群发消息 * * @param message * @throws IOException */ public static void BroadCastInfo(String message) throws IOException { for (Session session : SessionSet) { //判断如果websocket链接如果是开启的情况下,则发送信息 if (session.isOpen()) { SendMessage(session, message); } } } /** * 指定Session发送消息 * * @param sessionId * @param message * @throws IOException */ public static void SendMessage(String sessionId, String message) throws IOException { Session session = null; for (Session s : SessionSet) { if (s.getId().equals(sessionId)) { session = s; break; } } if (session != null) { SendMessage(session, message); } else { log.warn("没有找到你指定ID的会话:{}", sessionId); } } }
定时发送
@Scheduled(cron = "*/3 * * * * *") @ResponseBody @GetMapping("/websocke") public void webSocket() { String s = "hello world"; try { MyWebSocket.BroadCastInfo(s); } catch (IOException e) { System.out.println("执行异常"); e.printStackTrace(); } }
入口文件开启
@SpringBootApplication @EnableScheduling public class WebsocketApplication { public static void main(String[] args) { SpringApplication.run(WebsocketApplication.class, args); } }
前端内容