`

转帖:websocket+java+tomcat推送数据到前台

阅读更多

转帖地址:http://blog.csdn.net/u011181882/article/details/53311215

原地址:http://blog.chenzuhuang.com/archive/28.html

步骤:

1、新建html页面,代码如下

2、新建java类,代码如下

3、要求:Tomcat从7.0.27开始支持WebSocket,从7.0.47开始支持JSR-356,下面的Demo代码也是需要部署在Tomcat7.0.47上才能运行。

前端代码:

 

[html] view plain copy
 
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="UTF-8">  
  5.     <title>webSocketTest</title>  
  6. </head>  
  7. <body>  
  8. <input id="text" type="text" /><button onclick="send()">Send</button>  
  9. <button onclick="closeWebSocket()">Close</button>  
  10. <div id="message"></div>  
  11. </body>  
  12. <script type="text/javascript">  
  13.     var websocket = null;  
  14.   
  15.     //判断当前浏览器是否支持WebSocket  
  16.     if('WebSocket' in window){  
  17.         websocket = new WebSocket("ws://localhost:8080/SpringMVCTutorial/websocket");  
  18.     }  
  19.     else{  
  20.         alert('Not support websocket')  
  21.     }  
  22.   
  23.     //连接发生错误的回调方法  
  24.     websocket.onerror = function(){  
  25.         setMessageInnerHTML("error");  
  26.     };  
  27.   
  28.     //连接成功建立的回调方法  
  29.     websocket.onopen = function(event){  
  30.         setMessageInnerHTML("open");  
  31.     }  
  32.   
  33.     //接收到消息的回调方法  
  34.     websocket.onmessage = function(event){  
  35.         setMessageInnerHTML(event.data);  
  36.     }  
  37.   
  38.     //连接关闭的回调方法  
  39.     websocket.onclose = function(){  
  40.         setMessageInnerHTML("close");  
  41.     }  
  42.   
  43.     //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。  
  44.     window.onbeforeunload = function(){  
  45.         websocket.close();  
  46.     }  
  47.   
  48.     //将消息显示在网页上  
  49.     function setMessageInnerHTML(innerHTML){  
  50.         document.getElementById('message').innerHTML += innerHTML + '<br/>';  
  51.     }  
  52.   
  53.     //关闭连接  
  54.     function closeWebSocket(){  
  55.         websocket.close();  
  56.     }  
  57.   
  58.     //发送消息  
  59.     function send(){  
  60.         var message = document.getElementById('text').value;  
  61.         websocket.send(message);  
  62.     }  
  63. </script>  
  64. </html>  

后台java代码:

[html] view plain copy
 
  1. package com.springmvc.websocket;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.concurrent.CopyOnWriteArraySet;  
  5.    
  6. import javax.websocket.OnClose;  
  7. import javax.websocket.OnError;  
  8. import javax.websocket.OnMessage;  
  9. import javax.websocket.OnOpen;  
  10. import javax.websocket.Session;  
  11. import javax.websocket.server.ServerEndpoint;  
  12.    
  13. //该注解用来指定一个URI,客户端可以通过这个URI来连接到WebSocket。类似Servlet的注解mapping。无需在web.xml中配置。  
  14. @ServerEndpoint("/websocket")  
  15. public class MyWebSocket {  
  16.     //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。  
  17.     private static int onlineCount = 0;  
  18.        
  19.     //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识  
  20.     private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();  
  21.        
  22.     //与某个客户端的连接会话,需要通过它来给客户端发送数据  
  23.     private Session session;  
  24.        
  25.     /**  
  26.      * 连接建立成功调用的方法  
  27.      * @param session  可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据  
  28.      */  
  29.     @OnOpen  
  30.     public void onOpen(Session session){  
  31.         this.session = session;  
  32.         webSocketSet.add(this);     //加入set中  
  33.         addOnlineCount();           //在线数加1  
  34.         System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());  
  35.     }  
  36.        
  37.     /**  
  38.      * 连接关闭调用的方法  
  39.      */  
  40.     @OnClose  
  41.     public void onClose(){  
  42.         webSocketSet.remove(this);  //从set中删除  
  43.         subOnlineCount();           //在线数减1      
  44.         System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());  
  45.     }  
  46.        
  47.     /**  
  48.      * 收到客户端消息后调用的方法  
  49.      * @param message 客户端发送过来的消息  
  50.      * @param session 可选的参数  
  51.      */  
  52.     @OnMessage  
  53.     public void onMessage(String message, Session session) {  
  54.         System.out.println("来自客户端的消息:" + message);  
  55.            
  56.         //群发消息  
  57.         for(MyWebSocket item: webSocketSet){               
  58.             try {  
  59.                 item.sendMessage(message);  
  60.             } catch (IOException e) {  
  61.                 e.printStackTrace();  
  62.                 continue;  
  63.             }  
  64.         }  
  65.     }  
  66.        
  67.     /**  
  68.      * 发生错误时调用  
  69.      * @param session  
  70.      * @param error  
  71.      */  
  72.     @OnError  
  73.     public void onError(Session session, Throwable error){  
  74.         System.out.println("发生错误");  
  75.         error.printStackTrace();  
  76.     }  
  77.        
  78.     /**  
  79.      * 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。  
  80.      * @param message  
  81.      * @throws IOException  
  82.      */  
  83.     public void sendMessage(String message) throws IOException{  
  84.         this.session.getBasicRemote().sendText(message);  
  85.         //this.session.getAsyncRemote().sendText(message);  
  86.     }  
  87.    
  88.     public static synchronized int getOnlineCount() {  
  89.         return onlineCount;  
  90.     }  
  91.    
  92.     public static synchronized void addOnlineCount() {  
  93.         MyWebSocket.onlineCount++;  
  94.     }  
  95.        
  96.     public static synchronized void subOnlineCount() {  
  97.         MyWebSocket.onlineCount--;  
  98.     }  
  99. }  

用到的maven依赖:

 

[html] view plain copy
 
  1. <dependency>  
  2.     <groupId>javax.websocket</groupId>  
  3.     <artifactId>javax.websocket-api</artifactId>  
  4.     <version>1.1</version>  
  5. </dependency>  



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics