java+html实现webSoket通讯

本文内容是基于腾讯云TRTCCalling API 实现的简单webSoketDemo,内容包含客户端、服务端消息互动,客户端重连、心跳机制。
腾讯云TRTCSDK 腾讯云TRTCCalling
API(桌面浏览器)

腾讯云LocalStream

效果图

在这里插入图片描述

Controller类

package com.cgjd.web.controller.system;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

/**
 *  webSoket demo
 * @author : ljl
 * @date : 14:35 2021/3/19
 */
@Controller
public class TestWebSoketController {
   

    @GetMapping("/soket")
    public String soket(){
   
        return "webSoketDemo";
    }
}

Service类

package com.cgjd.socket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * WebSocketService 通讯
 *
 * @author : ljl
 * @date : 14:06 2021/2/24
 */
@Component
@Slf4j
@ServerEndpoint(value = "/app/websocketServer/{identityId}", configurator = MySpringConfigurator.class)
public class WebSocketService {
   

    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    // 线程安全全局变量
    private static ThreadLocal<Integer> t1 = new ThreadLocal<Integer>();

    //connect key为身份ID,value为此对象this
    public static Map<String, Object> clients = new ConcurrentHashMap<String, Object>();

    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    public Session session;

    /**
     * 连接建立成功调用的方法
     *
     * @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
     */
    @OnOpen
    public void onOpen(@PathParam("identityId") String identityId, Session session) {
   
        this.session = session;
        clients.put(identityId, this); // this = WebSocketService对象
        log.info("=========={}连接成功!当前在线人数为{}", identityId, clients.size());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(@PathParam("identityId") String identityId) {
   
        clients.remove(identityId);
        log.info("=========={}退出!当前在线人数为{}", identityId, clients.size());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param identityId 客户端发送过来的消息
     * @param message 可选的参数
     */
    @OnMessage
    public void onMessage(@PathParam("identityId") String identityId, String message) {
   
        if ("all".equals(message)){
   
            String str = "系统管理员对所有人说你好";
            sendToAll(str);
        }else {
   
            String str = "系统管理员" + "对你【" + identityId + "】说:已收到消息【" + message + "】";
            sendToUser(identityId, str);
        }
    }

    /**
     * 发生错误时调用
     *
     * @param identityId
     * @param error
     */
    @OnError
    public void
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值