ITeye博客

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

BreakingBad · 2017-12-08 18:24 · java高级 · 编程语言 · Markdown

转帖地址: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. //判断当前浏览器是否支持WebSocket
  15. if('WebSocket' in window){
  16. websocket = new WebSocket("ws://localhost:8080/SpringMVCTutorial/websocket");
  17. }
  18. else{
  19. alert('Not support websocket')
  20. }
  21. //连接发生错误的回调方法
  22. websocket.onerror = function(){
  23. setMessageInnerHTML("error");
  24. };
  25. //连接成功建立的回调方法
  26. websocket.onopen = function(event){
  27. setMessageInnerHTML("open");
  28. }
  29. //接收到消息的回调方法
  30. websocket.onmessage = function(event){
  31. setMessageInnerHTML(event.data);
  32. }
  33. //连接关闭的回调方法
  34. websocket.onclose = function(){
  35. setMessageInnerHTML("close");
  36. }
  37. //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
  38. window.onbeforeunload = function(){
  39. websocket.close();
  40. }
  41. //将消息显示在网页上
  42. function setMessageInnerHTML(innerHTML){
  43. document.getElementById('message').innerHTML += innerHTML + '<br/>';
  44. }
  45. //关闭连接
  46. function closeWebSocket(){
  47. websocket.close();
  48. }
  49. //发送消息
  50. function send(){
  51. var message = document.getElementById('text').value;
  52. websocket.send(message);
  53. }
  54. </script>
  55. </html>

后台java代码:

[html] view plain copy

 

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

用到的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>

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。