vue + Java 使用 WebSocket

配置

 <dependency>
	<groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

配置WebSocket Bean

@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointConfigurator(){
        return new ServerEndpointExporter();
    }

}

实现webSocket


@Component
@ServerEndpoint("/webSocket/{userId}")
public class WebSocket {

    private Session session;
    private static int onlineCount = 0;
    private static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>();
    private String userId;


    /**
     * 新建链接
     * @param userId
     * @param session
     */
    @OnOpen
    public void onOpen(@PathParam("userId") String userId,Session session){
        this.userId = userId;
        this.session=session;
        clients.put(this.userId, this);
        addOnlineCount();
        System.out.println("【websocket消息】有新的连接,总数:{}"+onlineCount);
    }

    /**
     * 断开链接
     */
    @OnClose
    public void onClose(){
        clients.remove(userId);
        subOnlineCount();
        System.out.println("【websocket消息】连接断开,总数:{}"+onlineCount);
    }

    /**
     * 接收消息
     * @param message
     */
    @OnMessage
    public void onMessage(String message){

        for (WebSocket item : clients.values()) {

            if (item.userId.equals(userId))

                item.session.getAsyncRemote().sendText(message);

        }

        System.out.println("【websocket消息】收到客户端发来的消息:{}"+message);
    }

    /**
     * 发送到指定用户
     * @param message
     * @param ToUserId
     */
    public static void sendMessageToUserId(String message, String ToUserId){

        for (WebSocket item : clients.values()) {

            if (item.userId.equals(ToUserId))

                item.session.getAsyncRemote().sendText(message);

        }

    }

    /**
     * 查询是否创建链接
     * @param ToUserId
     */
    public static int findToUserId(String ToUserId){
        int count = 0;

        for (WebSocket item : clients.values()) {

            if (item.userId.equals(ToUserId)){
                count++;
            }
        }
        return count;
    }

    /**
     * 消息发送给所有用户
     * @param message
     */
    public void sendMessageAll(String message){

        for (WebSocket item : clients.values()) {

            item.session.getAsyncRemote().sendText(message);

        }

    }

    public static synchronized int getOnlineCount() {

        return onlineCount;

    }

    public static synchronized void addOnlineCount() {

        WebSocket.onlineCount++;

    }

    public static synchronized void subOnlineCount() {

        WebSocket.onlineCount--;

    }

    public static synchronized Map<String, WebSocket> getClients() {

        return clients;

    }

}

页面链接WebSocket

//当前浏览器是否支持websocket
    if ("WebSocket" in window) {
      const ws = new WebSocket("ws://192.168.0.113:8102/rabbit/webSocket/" + userId);

      // 初次连接
      ws.onopen = () => {
        console.log("初次连接");
      };
      // 发送
      ws.onmessage = (res) => {
        console.log(res.data);
      };
      ws.onerror = () => {
        console.log("异常");
      };
      ws.onclose = () => {
        console.log("关闭链接");
      };
      //当前浏览器页面关闭了 此时应该关闭链接
      // 生命周期
      onUnmounted(() => {
        console.log("关闭");
        ws.close(); //关闭
      });
    } else {
      console.log("不支持WebSocket");
    }
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值