SpringBoot 快速实现WebSocket
来源:互联网 发布:零食数据 编辑:程序博客网 时间:2024/06/08 10:05
SpringBoot 快速实现WebSocket
1.添加Maven依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> <version>1.3.5.RELEASE</version></dependency>
2.webSocket配置
/** * webSocket配置 * @author 陈梓平 * @date 2017/10/25. */@Configurationpublic class WebSocketConfig { /** * 注入ServerEndpointExporter, * 这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint * @return */ @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); }}
3.自定义websocket
/** * 自定义websocket * @author 陈梓平 * @date 2017/10/25. */@ServerEndpoint(value = "/websocket")@Componentpublic class CustomWebSocket { /**静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。*/ private static int onlineCount = 0; /**concurrent包的线程安全Set,用来存放每个客户端对应的CumWebSocket对象。*/ private static CopyOnWriteArraySet<CustomWebSocket> webSocketSet = new CopyOnWriteArraySet<CustomWebSocket>(); /**与某个客户端的连接会话,需要通过它来给客户端发送数据*/ private Session session; private static final Logger log = LoggerFactory.getLogger(CustomWebSocket.class); /** * 连接建立成功调用的方法 * @param session */ @OnOpen public void onOpen(Session session) { this.session = session; //加入set中 webSocketSet.add(this); //添加在线人数 addOnlineCount(); log.info("新连接接入。当前在线人数为:"+getOnlineCount()); try { sendMessage("假装有内容"); } catch (IOException e) { e.printStackTrace(); } } /** * 连接关闭调用的方法 */ @OnClose public void onClose() { //从set中删除 webSocketSet.remove(this); //在线数减1 subOnlineCount(); log.info("有连接关闭。当前在线人数为:"+getOnlineCount()); } /** * 收到客户端消息后调用 * @param message * @param session */ @OnMessage public void onMessage(String message, Session session) { log.info("客户端发送的消息:"+message); sendAll(message); } /** * 暴露给外部的群发 * @param message * @throws IOException */ public static void sendInfo(String message) throws IOException { sendAll(message); } /** * 群发 * @param message */ private static void sendAll(String message) { Arrays.asList(webSocketSet.toArray()).forEach(item -> { CustomWebSocket customWebSocket = (CustomWebSocket) item; //群发 try { customWebSocket.sendMessage(message); } catch (IOException e) { e.printStackTrace(); } }); } /** * 发生错误时调用 * @param session * @param error */ @OnError public void onError(Session session, Throwable error) { log.info("有异常啦"); error.printStackTrace(); } /** * 减少在线人数 */ private void subOnlineCount() { CustomWebSocket.onlineCount--; } /** * 添加在线人数 */ private void addOnlineCount() { CustomWebSocket.onlineCount++; } /** * 当前在线人数 * @return */ public static synchronized int getOnlineCount() { return onlineCount; } /** * 发送信息 * @param message * @throws IOException */ public void sendMessage(String message) throws IOException { //获取session远程基本连接发送文本消息 this.session.getBasicRemote().sendText(message); //this.session.getAsyncRemote().sendText(message); }}
4.前端页面
<!DOCTYPE HTML><html><head> <title>WebSocket</title></head><body>Welcome<br/><input id="text" type="text" /><button onclick="send()">Send</button> <button onclick="closeWebSocket()">Close</button><div id="message"></div></body><script type="text/javascript"> var websocket = null; //判断当前浏览器是否支持WebSocket if('WebSocket' in window){ websocket = new WebSocket("ws://localhost:8080/websocket"); } else{ alert('Not support websocket') } //连接发生错误的回调方法 websocket.onerror = function(){ setMessageInnerHTML("error"); }; //连接成功建立的回调方法 websocket.onopen = function(event){ setMessageInnerHTML("open"); } //接收到消息的回调方法 websocket.onmessage = function(event){ setMessageInnerHTML(event.data); } //连接关闭的回调方法 websocket.onclose = function(){ setMessageInnerHTML("close"); } //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。 window.onbeforeunload = function(){ websocket.close(); } //将消息显示在网页上 function setMessageInnerHTML(innerHTML){ document.getElementById('message').innerHTML += innerHTML + '<br/>'; } //关闭连接 function closeWebSocket(){ websocket.close(); } //发送消息 function send(){ var message = document.getElementById('text').value; websocket.send(message); }</script></html>
5.测试
阅读全文
1 0
- SpringBoot 快速实现WebSocket
- 使用SpringBoot快速搭建WebSocket实现消息推送
- SpringBoot WebSocket 实现简单的聊天功能
- springboot websocket
- SpringBoot-Websocket
- SpringBoot + WebSocket
- SpringBoot快速实现跨域
- SpringBoot中WebSocket不能实现注入的问题
- SpringBoot 实现WebSocket进行消息发送(适用于SpringMVC)
- SpringBoot 整合 Websocket 实现消息推送框架的设计笔记
- springBoot整合webSocket
- SpringBoot整合WebSocket案例
- SpringBoot之WebSocket练习
- SpringBoot中的WebSocket广播
- SpringBoot集成WebSocket
- SpringBoot 使用WebSocket
- springboot-websocket作为客户端
- SpringBoot 配置 WebSocket
- iptables实现网络防火墙(二)——SNAT与DNAT
- weblogic用户被锁与解锁
- 7. Declare destructors virtual in polymorphic base classes.
- IS-IS邻居建立
- 【个人笔记】android studio gradle 两种更新方法更新
- SpringBoot 快速实现WebSocket
- Android设计中的.9.png
- 广州棒谷笔试总结
- SimpleDateFormat需要sdk最低版本号为24的问题
- mysql触发器——DELIMITER 命令
- P2P传输的开源库:Libjingle库 综述
- ios中创建单例的作用(模仿网易新闻客户端)
- 模拟器Genymotion的安装与使用
- 谈谈Block作为属性、方法参数、方法的返回值的应用