WebSocket实时消息推送

摘要:
最近在项目中,使用到了WebSocket来实时推送服务器的数据到客户端,今天来记录总结一下。想要使用WebSocket来实时推送数据,首先需要服务器与客户端直接建立连接,也就是握手每5秒钟发生一个心跳@Scheduled(cron="0/5****?")publicvoidsendHeart(){MessageWebSocket.broadcast;}后端重要的代码:ServerEndpoint@Component@Slf4jpublicclassMessageWebSocket{/***concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象.*/privatestaticMapmapUserId=newConcurrentHashMap();/***与某个客户端的连接会话,需要通过它来给客户端发送数据.*/privateSessionsession;/***接收userId.*/privateStringuserId="";/***.连接建立成功调用的方法*/@OnOpenpublicvoidonOpen{this.session=session;this.userId=userId;mapUserId.put;log.info;try{send;}catch{e.printStackTrace();log.error("用户:"+userId+",网络异常!!!!!!

最近在项目中,使用到了WebSocket来实时推送服务器的数据到客户端,今天来记录总结一下。

想要使用WebSocket来实时推送数据,首先需要服务器与客户端直接建立连接,也就是握手(HTTP协议)

  每5秒钟发生一个心跳
@Scheduled(cron = "0/5 * * * * ? ") public void sendHeart() { MessageWebSocket.broadcast(new WebSocketMessage(WebSocketMessage.CMD_HEART, "SUCCESS")); }

后端重要的代码:

ServerEndpoint("/ws/{userId}")
@Component
@Slf4j
public class MessageWebSocket {

  /**
   * concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象.
   */
  private static Map<String, MessageWebSocket> mapUserId = new ConcurrentHashMap<>();
  /**
   * 与某个客户端的连接会话,需要通过它来给客户端发送数据.
   */
  private Session session;
  /**
   * 接收userId.
   */
  private String userId = "";

  /**
   * . 连接建立成功调用的方法
   */
  @OnOpen
  public void onOpen(Session session, @PathParam("userId") String userId) {
    this.session = session;
    this.userId = userId;
    mapUserId.put(userId, this);
    log.info("用户连接:" + userId);
    try {
      send(JSON.toJSONString(new WebSocketMessage(WebSocketMessage.CMD_CONN, "SUCCESS")));
    } catch (IOException e) {
      e.printStackTrace();
      log.error("用户:" + userId + ",网络异常!!!!!!");
    }
  }

  /**
   * . 连接关闭调用的方法
   */
  @OnClose
  public void onClose() {
    mapUserId.remove(userId);
  }

  /**
   * . 收到客户端消息后调用的方法
   *
   * @param message 客户端发送过来的消息
   */
  @OnMessage
  public void onMessage(String message, Session session) {
    log.info("user id:" + userId + ",message:" + message);
  }

  /**
   * .
   *
   * @param session 回话
   * @param error 错误信息
   */
  @OnError
  public void onError(Session session, Throwable error) {
    log.error("user id:" + this.userId + ",reason:" + error.getMessage());
    error.printStackTrace();
  }

  /**
   * . 实现服务器主动推送
   */
  public void send(String message) throws IOException {
    if (this.session != null) {
      synchronized (session) {
        this.session.getBasicRemote().sendText(message);
      }
    }
  }

  /**
   * . 实现服务器主动推送
   */
  public static void send(String userId, String message) throws IOException {
    MessageWebSocket socket = mapUserId.get(userId);
    if (socket != null) {
      try {
        socket.send(message);
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

  /**
   * 广播发送.
   *
   * @param message webSocket消息
   */
  public static void broadcast(WebSocketMessage message) {
    if (null == message) {
      return;
    }
    String content = JSON.toJSONString(message);
    //log.info("message :{}", content);
    for (String userId : mapUserId.keySet()) {
      try {
        send(userId, content);
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}

前端代码(VUE):百度搜索前端连接WebSocket

 methods: {
            initWebSocket() { //初始化weosocket
                const wsuri = "ws://127.0.0.1:8080";
                this.websock = new WebSocket(wsuri);
                this.websock.onmessage = this.websocketonmessage;
                this.websock.onopen = this.websocketonopen;
                this.websock.onerror = this.websocketonerror;
                this.websock.onclose = this.websocketclose;
            },
            websocketonopen() { //连接建立之后执行send方法发送数据
                let actions = {
                    "test": "123"
                };
                this.websocketsend(JSON.stringify(actions));
            },
            websocketonerror() { //连接建立失败重连
                this.initWebSocket();
            },
            websocketonmessage(e) { //数据接收
                const redata = JSON.parse(e.data);
            },
            websocketsend(Data) { //数据发送
                this.websock.send(Data);
            },
            websocketclose(e) { //关闭
                console.log('断开连接', e);
            },
        }

免责声明:文章转载自《WebSocket实时消息推送》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇定时器67事——捕获比较通道Qt使用.lib静态库和.dll动态库文件下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

把大文件切割成小文件

package com.jm.label.tools;/*** 把大文件切割成小文件*/import java.io.File;import java.io.FileInputStream; import java.io.FileNotFoundException;import java.io.FileOutputStream; import java.io...

C#格式化数值结果表

C#格式化数值结果表 字符 说明 示例 输出 C 货币 string.Format("{0:C3}", 2) $2.000 D 十进制 string.Format("{0:D3}", 2) 002 E 科学计数法 1.20E+001 1.20E+001 G 常规 string.Format("{0:G}", 2) 2 N 用...

(七) SpringBoot起飞之路-整合SpringSecurity(Mybatis、JDBC、内存)

兴趣的朋友可以去了解一下前五篇,你的赞就是对我最大的支持,感谢大家! (一) SpringBoot起飞之路-HelloWorld (二) SpringBoot起飞之路-入门原理分析 (三) SpringBoot起飞之路-YAML配置小结(入门必知必会) (四) SpringBoot起飞之路-静态资源处理 (五) SpringBoot起飞之路-Thymel...

从零搭建 ES 搜索服务(五)搜索结果高亮

一、前言 在实际使用中搜索结果中的关键词前端通常会以特殊形式展示,比如标记为红色使人一目了然。我们可以通过 ES 提供的高亮功能实现此效果。 二、代码实现 前文查询是通过一个继承 ElasticsearchRepository 的接口实现的,但是如果要实现高亮,这种方式就满足不了了,这里我们需要通过 ElasticsearchTemplate 来完成。...

java反射知识点总结

一.java反射基础 1.1 什么叫java反射? 答:程序运行期间,动态的获取类的基本信息。比如:创建对象,调用类的方法,获得类的基本结构。这样给程序设计提供了很大的灵活性。个人总结就是:根据动态需求,生成动态的响应。java的Class类是java反射机制的基础,反射也是让虚拟机加载指定类。这就用到了java的类装载机制,jvm加载字节码文件,并生成c...

java登录拦截Filter

此例子为一个简单的登录拦截。 首先在web.xml中配置拦截类。 <filter-mapping> <filter-name>SessionFilter</filter-name> <url-pattern>/*</url-pattern> &...