本文内容是基于腾讯云TRTCCalling API 实现的简单webSoketDemo,内容包含客户端、服务端消息互动,客户端重连、心跳机制。
腾讯云TRTCSDK 腾讯云TRTCCalling
API(桌面浏览器)
腾讯云LocalStream
webSoket通讯
效果图
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