springboot + websocket

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35568099/article/details/82954194

 

1.引入pom依赖

 
  1. <dependency>

  2. <groupId>org.springframework.boot</groupId>

  3. <artifactId>spring-boot-starter-websocket</artifactId>

  4. </dependency>

2.新建websocket的服务

WebSocketServer.java
 
  1. /**

  2. * @Author: wyb

  3. * @Date: 2018/7/12 20:04

  4. * @Description:websoceket具体业务实现

  5. */

  6. @ServerEndpoint(value = "/websocket")

  7. @Component

  8. public class WebSocketServer {

  9. private final Logger logger = LoggerFactory.getLogger(this.getClass());

  10. //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。

  11. private static int onlineCount = 0;

  12.  
  13. //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。

  14. private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

  15.  
  16. //与某个客户端的连接会话,需要通过它来给客户端发送数据

  17. private Session session;

  18.  
  19. /**

  20. * 连接建立成功调用的方法*/

  21. @OnOpen

  22. public void onOpen(Session session) {

  23. this.session = session;

  24. webSocketSet.add(this); //加入set中

  25. addOnlineCount(); //在线数加1

  26. }

  27.  
  28. /**

  29. * 连接关闭调用的方法

  30. */

  31. @OnClose

  32. public void onClose() {

  33. webSocketSet.remove(this); //从set中删除

  34. subOnlineCount(); //在线数减1

  35. }

  36.  
  37. /**

  38. * 收到客户端消息后调用的方法

  39. *

  40. * @param message 客户端发送过来的消息*/

  41. @OnMessage

  42. public void onMessage(String message, Session session) {

  43. System.out.println("来自客户端的心跳:" + message);

  44. }

  45.  
  46. /**

  47. * 发生错误时调用

  48. @OnError

  49. **/

  50. public void onError(Session session, Throwable error) {

  51. if(error != null)

  52. logger.error("WebSocketServer onError:" + error.getMessage());

  53. }

  54.  
  55.  
  56. /***

  57. * 对单一客户发送推送消息

  58. * @param message 消息内容

  59. */

  60. public void sendMessage(String message){

  61. try{

  62. this.session.getBasicRemote().sendText(message);

  63. }catch (Exception ex){

  64. logger.error("WebSocketServer sendMessage:" + ex.getMessage());

  65. }

  66. }

  67.  
  68.  
  69. /**

  70. * 群发自定义消息

  71. * */

  72. public static void broadcastSendInfo(String message){

  73. try{

  74. for (WebSocketServer item : webSocketSet) {

  75. item.sendMessage(message);

  76. }

  77. }catch (Exception ex){

  78. System.out.println(ex.getMessage());

  79. }

  80.  
  81. }

  82.  
  83. public static synchronized void addOnlineCount() {

  84. WebSocketServer.onlineCount++;

  85. }

  86.  
  87. public static synchronized void subOnlineCount() {

  88. WebSocketServer.onlineCount--;

  89. }

  90. }

3.向spring注入bean

 
  1. @Bean

  2. public ServerEndpointExporter serverEndpointExporter() {

  3. return new ServerEndpointExporter();

  4. }

4.添加websocket的js

MyWebSocket.js
 
  1. /**

  2. * Created by PC on 2018/2/11.

  3. */

  4. var heartflag = true;

  5. var webSocket = null;

  6. var tryTime = 0;

  7. $(function () {

  8. initSocket();

  9. });

  10.  
  11. /**

  12. * 初始化websocket,建立连接

  13. */

  14. function initSocket() {

  15.  
  16. if (!window.WebSocket) {

  17. alert("您的浏览器不支持推送功能");

  18. return false;

  19. }

  20. webSocket = null;

  21. webSocket = new WebSocket("ws://" + window.location.host + "/websocket");

  22.  
  23. // 收到服务端消息

  24. webSocket.onmessage = function (msg) {

  25. if(msg.data == "&"){

  26. // 暂时不用服务器反向发送心跳

  27. }else{

  28. popmsg(msg.data);

  29. }

  30. };

  31.  
  32. // 异常

  33. webSocket.onerror = function (event) {

  34. heartflag = false;

  35. };

  36.  
  37. // 建立连接

  38. webSocket.onopen = function (event) {

  39. heartflag = true;

  40. heart();

  41. tryTime = 0;

  42. };

  43.  
  44. // 断线重连

  45. webSocket.onclose = function () {

  46. heartflag = false;

  47. tryTime++;

  48. // 重试10次,每次之间间隔1秒

  49. if (tryTime < 10) {

  50. setTimeout(function () {

  51. if(!heartflag){

  52. webSocket = null;

  53. initSocket();

  54. //alert("第:" + tryTime + "次重新建链。");

  55. }

  56. }, 1000);

  57. } else {

  58. //alert("重连失败.");

  59. }

  60. };

  61.  
  62. heartflag = true;

  63.  
  64. }

  65. // 连接成功后发送心跳

  66. function heart() {

  67. if (heartflag){

  68. webSocket.send("&");

  69. }

  70. setTimeout("heart()", 10*1000);

  71.  
  72. }

  73.  
  74. function popmsg(popmsg){

  75. //配置一个透明的询问框

  76. layer.msg('', {

  77. time: 20000, //20s后自动关闭

  78. offset: 'rb',

  79. content: '<div style="padding: 20px 100px;">'+ popmsg +'</div>'

  80. });

  81. }

这里显示使用了layer的部分内容

请注意最好建立心跳,因为如果不建立心跳那么网络中存在问题将有可能无法发现线路断链。

猜你喜欢

转载自blog.csdn.net/qq_35568099/article/details/82954194