websocket学习

html 复制代码
<!DOCTYPE html>
<html>
<head>
    <title>WebSocket Example</title>
    <script>
        let socket = new WebSocket("http://localhost:8081/api/websocket/{userid}");
        let heartbeatInterval;

        // 当 WebSocket 连接打开时执行
        socket.onopen = function(event) {
            console.log("WebSocket is open.");
            startHeartbeat(); // 开始心跳
        };

        // 当收到消息时执行
        socket.onmessage = function(event) {
            console.log("Received message: " + event.data);
            // 在此处理接收到的消息
        };

        // 发送心跳消息
        function sendHeartbeat() {
            console.log("Sending heartbeat...");
            socket.send("heartbeat");
        }

        // 开始心跳定时器
        function startHeartbeat() {
            heartbeatInterval = setInterval(sendHeartbeat, 5000); // 每5秒发送一次心跳
        }

        // 当 WebSocket 连接关闭时执行
        socket.onclose = function(event) {
            console.log("WebSocket is closed.");
            clearInterval(heartbeatInterval); // 清除心跳定时器
        };
        function sendMessage() {
            let message = document.getElementById("message").value;
            socket.send(message);
        }
</script>
</head>
<body>
<input type="text" id="message" placeholder="Type a message..."> <!-- 输入框,用于输入消息 -->
<button onclick="sendMessage()">Send</button> <!-- 发送按钮,调用sendMessage函数发送消息 -->
</body>
</html>


```java
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverendpointExporter(){
        return new ServerEndpointExporter();
    }
}

@ServerEndpoint("/myWs/{userId}")
@Component
@Slf4j
public class WsServerEndPoint {
    // ConcurrentHashMap 和hashMap的区别是 ConcurrentHashMap是线程安全的
    static Map<String,Session> sessionMap = new ConcurrentHashMap<>();
    /**
     *  websocket建立链接时触发方法
     * @author liukang
     * @date 20:15 2024/5/18
     * @param session 每一个websocket的链接 对于服务端都是一个session
     **/
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId){
        // 建立连接时,将session存入map中 使用用户ID作为sessionMap的key
      sessionMap.put(userId,session);
      log.info("websocket is open");
      log.info(userId);
    }

    @OnMessage
    public String onMessage(String text){
        return null;
    }

    @OnClose
    public void onClose(Session session, @PathParam("userId") String userId){
        log.info(userId);
        sessionMap.remove(userId);
        log.info(("websocket is close"));
    }

    public void sendMsgToUser(MessagePo message) throws IOException {
        String toUserId = message.getToUser();
        Session session = sessionMap.get(toUserId);
        RemoteEndpoint.Basic basicRemote = session.getBasicRemote();
        ObjectMapper mapper = new ObjectMapper();
        String msgStr = mapper.writeValueAsString(message);
        basicRemote.sendText(msgStr);
    }

}
复制代码
相关推荐
一只小鱼儿吖2 分钟前
携趣HTTP代理浏览器设置器(PC版)使用指南
网络·网络协议·http
sww_102611 分钟前
JVM基础学习
jvm·学习·测试工具
num_killer37 分钟前
小白的Jenkins学习
运维·python·学习·jenkins
乾元1 小时前
企业无线的 AI 频谱与功率自动优化——从人工勘测到“可学习的无线网络”(含真实室内工程案例)
服务器·网络·人工智能·网络协议·安全·信息与通信
Every exam must be1 小时前
12.2 vue学习02
学习
meichao91 小时前
springboot3.5.8集成websocket问题
网络·spring boot·websocket·网络协议
sunfove1 小时前
照度 (E) 与亮度 (L) 的关系
学习
HL_风神1 小时前
设计原则之单一职责原则
c++·学习·设计模式·单一职责原则
CS创新实验室2 小时前
正态分布的深入学习:从数学发现到自然法则的演变
学习·数据挖掘·数据分析·统计学·正态分布