spring boot + websocket进行通信

这次给大家说一下自己对websocket + spring boot结合使用的一些经验

 

首先websocket是一个持久化的协议,实现了浏览器与服务器的全双工通信。不再像http那样,只有在浏览器发出request之后才有response,websocket能实现服务器主动向浏览器发出消息。

 

下面我们用spring boot来实现一下:

在spring boot的文档中,介绍了我们需要配置的文件

Java代码   收藏代码
  1. // pom.xml  
  2. <dependency>  
  3.             <groupId>org.springframework.boot</groupId>  
  4.             <artifactId>spring-boot-starter-websocket</artifactId>  
  5. </dependency>  
 
之后我们需要添加一个单例bean,名为ServerEndpointExporter
Java代码   收藏代码
  1. @Configuration  
  2. public class WebSocketConfig {  
  3.     @Bean  
  4.     public ServerEndpointExporter serverEndpointExporter (){  
  5.         return new ServerEndpointExporter();  
  6.     }  
  7. }  
 
接下来便能使用websocket了,下面是一个简单的例子:
Java代码   收藏代码
  1. @ServerEndpoint("/websocket")  
  2. @Component  
  3. public class MyWebSocket {  
  4.   
  5.     private static int onlineCount = 0;  
  6.   
  7.     private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<>();  
  8.   
  9.     private Session session;  
  10.   
  11.     @OnOpen  
  12.     public void onOpen (Session session){  
  13.         this.session = session;  
  14.         webSocketSet.add(this);  
  15.         addOnlineCount();  
  16.         System.out.println("有新链接加入!当前在线人数为" + getOnlineCount());  
  17.     }  
  18.   
  19.     @OnClose  
  20.     public void onClose (){  
  21.         webSocketSet.remove(this);  
  22.         subOnlineCount();  
  23.         System.out.println("有一链接关闭!当前在线人数为" + getOnlineCount());  
  24.     }  
  25.   
  26.     @OnMessage  
  27.     public void onMessage (String message, Session session) throws IOException {  
  28.         System.out.println("来自客户端的消息:" + message);  
  29.         // 群发消息  
  30.         for ( MyWebSocket item : webSocketSet ){  
  31.                 item.sendMessage(message);  
  32.         }  
  33.     }  
  34.   
  35.     public void sendMessage (String message) throws IOException {  
  36.         this.session.getBasicRemote().sendText(message);  
  37.     }  
  38.   
  39.     public static synchronized  int getOnlineCount (){  
  40.         return MyWebSocket.onlineCount;  
  41.     }  
  42.   
  43.     public static synchronized void addOnlineCount (){  
  44.         MyWebSocket.onlineCount++;  
  45.     }  
  46.   
  47.     public static synchronized void subOnlineCount (){  
  48.         MyWebSocket.onlineCount--;  
  49.     }  
  50.   
  51. }  
 
代码很简单,相信大家都能看懂,接下来贴一下html代码:
Java代码   收藏代码
  1. <!DOCTYPE HTML>  
  2. <html>  
  3. <head>  
  4.     <base href="localhost://localhost:8080/">  
  5.     <title>My WebSocket</title>  
  6. </head>  
  7.   
  8. <body>  
  9. Welcome<br/>  
  10. <input id="text" type="text"/>  
  11. <button οnclick="send()">Send</button>  
  12. <button οnclick="closeWebSocket()">Close</button>  
  13. <div id="message">  
  14. </div>  
  15. </body>  
  16.   
  17. <script type="text/javascript">  
  18.     var websocket = null;  
  19.   
  20.     //判断当前浏览器是否支持WebSocket  
  21.     if ('WebSocket' in window) {  
  22.         websocket = new WebSocket("ws://localhost:8080/websocket");  
  23.     }  
  24.     else {  
  25.         alert('Not support websocket')  
  26.     }  
  27.   
  28.     //连接发生错误的回调方法  
  29.     websocket.onerror = function () {  
  30.         setMessageInnerHTML("error");  
  31.     };  
  32.   
  33.     //连接成功建立的回调方法  
  34.     websocket.onopen = function (event) {  
  35.         setMessageInnerHTML("open");  
  36.     }  
  37.   
  38.     //接收到消息的回调方法  
  39.     websocket.onmessage = function (event) {  
  40.         setMessageInnerHTML(event.data);  
  41.     }  
  42.   
  43.     //连接关闭的回调方法  
  44.     websocket.onclose = function () {  
  45.         setMessageInnerHTML("close");  
  46.     }  
  47.   
  48.     //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。  
  49.     window.onbeforeunload = function () {  
  50.         websocket.close();  
  51.     }  
  52.   
  53.     //将消息显示在网页上  
  54.     function setMessageInnerHTML(innerHTML) {  
  55.         document.getElementById('message').innerHTML += innerHTML + '<br/>';  
  56.     }  
  57.   
  58.     //关闭连接  
  59.     function closeWebSocket() {  
  60.         websocket.close();  
  61.     }  
  62.   
  63.     //发送消息  
  64.     function send() {  
  65.         var message = document.getElementById('text').value;  
  66.         websocket.send(message);  
  67.     }  
  68. </script>  
  69. </html>  

 

 
接下来便能直接启动websocket进行访问了,具体的扩展可以根据你的业务需求进行增加。
其实websocket就是基于http协议的升级,在http的headers中有一个header名为Upgrade,用来对http协议进行升级,从而换用其他的协议,在本例中,为Upgrade:websocket

评论
3 楼  xqlsrjjjh 2017-12-18  
亲测可用,上面所说的html放在src\main\resources\static目录下,名字为index.html,这样在一运行spring boot之后就可以访问到了
2 楼  k88520
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值