【Spring Boot 二十】聊聊Spring Boot 之 Websocket
什么是WebSocket
WebSocket为浏览器和服务器之间提供了双工异步通信功能,也就是说我们可以利用浏览器给服务器发送消息,服务器也可以给浏览器发送消息,目前主流浏览器的主流版本对WebSocket的支持都算是比较好的,但是在实际开发中使用WebSocket工作量会略大,而且增加了浏览器的兼容问题,这种时候我们更多的是使用WebSocket的一个子协议stomp,利用它来快速实现我们的功能。OK,关于WebSocket我这里就不再多说,我们主要看如何使用,如果小伙伴们有兴趣可以查看这个回答来了解更多关于WebSocket的信息WebSocket 是什么原理?为什么可以实现持久连接。
开始
1、导包
springboot的高级组件会自动引用基础的组件,像spring-boot-starter-websocket就引入了spring-boot-starter-web和spring-boot-starter,避免重复导入包~
1 2 3 4 |
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> |
2、新建包
com.spring.boot.websocket
3、新建类:WebSocketHandle.java、WebSocketConfig.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 |
package com.spring.boot.websocket; import org.springframework.stereotype.Component; import javax.websocket.*; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.util.concurrent.CopyOnWriteArraySet; /** * @ Author :XJH. * @ Date :Created in 16:57 2017/11/25. * @ Description:WebSocketHandle * @ Modified By: */ @Component @ServerEndpoint(value = "/websocket") public class WebSocketHandle { //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。 private static int onlineCount = 0; //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。 private static CopyOnWriteArraySet<WebSocketHandle> webSocketSet = new CopyOnWriteArraySet<>(); //与某个客户端的连接会话,需要通过它来给客户端发送数据 private Session session; /** * 连接建立成功调用的方法 */ @OnOpen public void onOpen(Session session, EndpointConfig config) { this.session = session; webSocketSet.add(this); //加入set中 addOnlineCount(); //在线数加1 System.out.println("有新连接加入!当前在线人数为" + getOnlineCount()); try { sendMessage("test"); } 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 (WebSocketHandle item : webSocketSet) { try { item.sendMessage(message); } catch (IOException e) { e.printStackTrace(); } } } /** * 发生错误时调用 * * @param session * @param error */ 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 static void sendInfo(String message) throws IOException { for (WebSocketHandle item : webSocketSet) { try { item.sendMessage(message); } catch (IOException e) { continue; } } } public static synchronized int getOnlineCount() { return onlineCount; } public static synchronized void addOnlineCount() { WebSocketHandle.onlineCount++; } public static synchronized void subOnlineCount() { WebSocketHandle.onlineCount--; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package com.spring.boot.websocket; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; @Configuration public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } } |
4、新建一个测试websocket的页面,放到resources/static下面:index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
<!DOCTYPE HTML> <html> <head> <title>WebSocket Test</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:8090/boot/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> |
然后就可以通过http://localhost:8090/boot/index.html访问了。
5、访问控制
此时,默认所有人都可以通过websocket连接,如果想控制访问权限,可以在shiro的配置文件拦截器加入
filterChainDefinitionMap.put("/websocket/**", "anon");
如果不加上面这句话,那么shiro会拦截websocket请求,返回未登录的信息。
6、websocket Session 转换 shiro Session
websocket的session和web容器的session是不同的session
websocket的session是:javax.websocket.Session
web容器我使用的Session是shiro,故:org.apache.shiro.session.Session
6.1创建类GetHttpSessionConfigurator.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
package com.spring.boot.websocket; import javax.servlet.http.HttpSession; import javax.websocket.HandshakeResponse; import javax.websocket.server.HandshakeRequest; import javax.websocket.server.ServerEndpointConfig; import javax.websocket.server.ServerEndpointConfig.Configurator; public class GetHttpSessionConfigurator extends Configurator { /** * class :GetHttpSessionConfigurator * method :modifyHandshake * description :获取httpSession * create by :XJH * create time :2017/11/25/025 * * @param sec * @param request * @param response * @return void */ @Override public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) { HttpSession httpSession = (HttpSession) request.getHttpSession(); sec.getUserProperties().put(HttpSession.class.getName(), httpSession); } } |
6.2WebSocketHandle类的ServerEndpoint注解修改如下
ServerEndpoint@ServerEndpoint(value = "/websocket",configurator=GetHttpSessionConfigurator.class)
6.3在WebSocketHandle中获得并使用httpSession
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
/** * 连接建立成功调用的方法 */ @OnOpen public void onOpen(Session session, EndpointConfig config) { HttpSession httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName()); session.getUserProperties().put(Const.HTTP_SESSION, httpSession); session.getUserProperties().put("http_session", httpSession); String sessionId = session.getId(); this.session = session; webSocketSet.add(this); //加入set中 addOnlineCount(); //在线数加1 System.out.println("有新连接加入!当前在线人数为" + getOnlineCount()); try { sendMessage("test"); } catch (IOException e) { System.out.println("IO异常"); } } |
在onOpen打开连接的时候通过传入EndpointConfig
HttpSession httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());获得httpSession
然后将httpSession存入websocket Session中
session.getUserProperties().put(Const.HTTP_SESSION, httpSession);
若在onClose()、onMessage()业务用到httpSession,可以传入websocket Session,通过websocket Session获得httpSession
HttpSession httpSession = (HttpSession) session.getUserProperties().get(Const.HTTP_SESSION);
人生的数据,需要自己一步一步的努力计算
XRumerTest
Hello. And Bye.