spring boot + websocket for communication

Go to http://zk-chs.iteye.com/blog/2285329

This time, I will tell you about some of my experience in the combination of websocket + spring boot

 

First of all, websocket is a persistent protocol that realizes full-duplex communication between the browser and the server. No longer like http, there is a response only after the browser sends a request, websocket can enable the server to actively send messages to the browser.

 

Let's use spring boot to implement it:

In the spring boot documentation, the files we need to configure are introduced

Java code   Favorite code
  1. // pom.xml  
  2. <dependency>  
  3.             <groupId>org.springframework.boot</groupId>  
  4.             <artifactId>spring-boot-starter-websocket</artifactId>  
  5. </dependency>  
  After that we need to add a singleton bean named ServerEndpointExporter
Java code   Favorite code
  1. @Configuration  
  2. public class WebSocketConfig {  
  3.     @Bean  
  4.     public ServerEndpointExporter serverEndpointExporter (){  
  5.         return new ServerEndpointExporter();  
  6.     }  
  7. }  
  Next, you can use websocket. Here is a simple example:
Java code   Favorite code
  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( "A new link is added! The current online number is"  + getOnlineCount());  
  17.     }  
  18.   
  19.     @OnClose  
  20.     public void onClose (){  
  21.         webSocketSet.remove(this);  
  22.         subOnlineCount();  
  23.         System.out.println( "A link is closed! The current online number is"  + getOnlineCount());  
  24.     }  
  25.   
  26.     @OnMessage  
  27.     public void onMessage (String message, Session session) throws IOException {  
  28.         System.out.println( "Message from client: "  + message);  
  29.         // group message  
  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. }  
  The code is very simple, I believe everyone can understand it, and then paste the html code:
Java code   Favorite code
  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 onclick="send()">Send</button>  
  12. <button onclick="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>  

 

  Next, you can directly start websocket for access, and specific extensions can be added according to your business needs. In fact, websocket is an upgrade based on the http protocol. There is a header named Upgrade in the http headers, which is used to upgrade the http protocol, so as to switch to other protocols. In this example, it is Upgrade:websocket

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327043184&siteId=291194637