websocket基于Springboot本人亲测
2018-02-04 14:34
453 查看
非常感谢https://www.cnblogs.com/bianzy/p/5822426.html
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>8.0</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-websocket -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>1.5.10.RELEASE</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>8.0</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-websocket -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>1.5.10.RELEASE</version>
</dependency>
package com.example.demo.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; /** * websocket * * @author huxu * @create 2018-02-04 11:04 **/ @Configuration public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } }
package com.example.demo; import org.springframework.stereotype.Component; import javax.websocket.*; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.util.concurrent.CopyOnWriteArraySet; /** * websocket的具体实现类 * * @author huxu * @create 2018-02-04 11:07 **/ @ServerEndpoint(value = "/websocket") @Component public class MyWebSocket { /** * 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。 */ private static int onlineCount = 0; /** * concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。 */ private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<>(); /** * 与某个客户端的连接会话,需要通过它来给客户端发送数据 */ private Session session; /** * 连接建立成功调用的方法*/ @OnOpen public void onOpen(Session session) { this.session = session; webSocketSet.add(this); //加入set中 addOnlineCount(); //在线数加1 System.out.println("有新连接加入!当前在线人数为" + getOnlineCount()); /*try { sendMessage(CommonConstant.CURRENT_WANGING_NUMBER.toString()); } catch (IOException e) { System.out.println("IO异常"); }*/ } /** * 连接关闭调用的方法 */ @OnClose public void onClose() { webSocketSet.remove(this); //从set中删除 subOnlineCount(); //在线数减1 System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount()); } /** * 收到客户端消息后调用的方法 * * @param message 客户端发送过来的消息*/ @OnMessage public void onMessage(String message, Session session) { System.out.println("来自客户端的消息:" + message); //群发消息 for (MyWebSocket item : webSocketSet) { try { item.sendMessage(message); } catch (IOException e) { e.printStackTrace(); } } } //发生错误时调用 @OnError public void onError(Session session, Throwable error) { System.out.println("发生错误"); error.printStackTrace(); } public void sendMessage(String message) throws IOException { this.session.getBasicRemote().sendText(message); //this.session.getAsyncRemote().sendText(message); } /** * 群发自定义消息 * */ public void sendInfo(String message) throws IOException { for (MyWebSocket item : webSocketSet) { try { item.sendMessage(message); } catch (IOException e) { continue; } } } public static synchronized int getOnlineCount() { return onlineCount; } public static synchronized void addOnlineCount() { MyWebSocket.onlineCount++; } public static synchronized void subOnlineCount() { MyWebSocket.onlineCount--; } }
package com.example.demo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author huxu * @create 2018-02-04 12:39 **/ @RestController @RequestMapping({"/", "/index"}) public class Demo { @Autowired private MyWebSocket myWebSocket; @PostMapping("/hello") public String sayBy() throws Exception { for (int i=0;i<1000; i++) { Thread.sleep(1000); System.out.println("发消息了:"+i); myWebSocket.sendInfo("推消息:"+i); } return "good bye"; } }
var websocket = null; //判断当前浏览器是否支持WebSocket if ('WebSocket' in window) { websocket = new WebSocket("ws://127.0.0.1:9090/websocket"); } else { alert('当前浏览器 Not support websocket') } //连接发生错误的回调方法 websocket.onerror = function () { setMessageInnerHTML("WebSocket连接发生错误"); }; //连接成功建立的回调方法 websocket.onopen = function () { setMessageInnerHTML("WebSocket连接成功"); } //接收到消息的回调方法 websocket.onmessage = function (event) { setMessageInnerHTML(event.data); } //连接关闭的回调方法 websocket.onclose = function () { setMessageInnerHTML("WebSocket连接关闭"); } //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。 window.onbeforeunload = function () { closeWebSocket(); } //将消息显示在网页上 function setMessageInnerHTML(innerHTML) { document.getElementById('message').innerHTML += innerHTML + '<br/>'; } //关闭WebSocket连接 function closeWebSocket() { websocket.close(); } //发送消息 function send() { var message = document.getElementById('text').value; websocket.send(message); }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>WebSocket测试</title> </head> <body> Welcome<br/> <input id="text" type="text"/> <button onclick="send()">发送消息</button> <hr/> <button onclick="closeWebSocket()">关闭WebSocket连接</button> <hr/> <div id="message"></div> <script src="js/WebSocket.js"></script> </body> </html>
相关文章推荐
- SpringBoot集成WebSocket【基于STOMP协议】进行点对点[一对一]和广播[一对多]实时推送
- SpringBoot的WebSocket基于STOMP协议自动广播推送配置
- java之Websocket后台(基于Spring boot)
- SpringBoot集成WebSocket【基于纯H5】进行点对点[一对一]和广播[一对多]实时推送
- 基于 SpringBoot 和 webSocket 的匿名聊天室
- Spring Boot 构建应用——基于 WebSocket 的消息推送
- 基于Spring Boot和Spring Cloud实现微服务架构学习(五)-Docker总结
- SpringBoot整合WebSocket案例
- Spring Boot 基于注解的 Redis 缓存使用详解
- 基于springboot+vue+element+ueditor实现前后端分离的富文本框实现
- 基于Spring Boot与Spring Data JPA的多数据源配置
- 非spring-boot调用基于spring-cloud + zookeeper微服务 - 基础搭建
- docker运行基于springboot的web项目
- Spring Boot 基于注解的 Redis 缓存使用
- 基于springboot+redis+bootstrap+mysql开发一套属于自己的分布式springcloud云权限架构(四)【构建链路调用监控系统】
- SpringBoot 集成WebSocket广播模式
- 基于spring-boot的rest微服务框架
- web即时通讯2--基于Spring websocket达到web聊天室
- spring boot 开发环境搭建,基于spring boot 1.4.2
- 在Spring Boot框架下使用WebSocket实现聊天功能