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);
    }

}
复制代码
相关推荐
摘星星的屋顶20 小时前
论文阅读记录之《VelocityGPT 》
论文阅读·人工智能·深度学习·学习
dreams_dream21 小时前
标准 HTTP 状态码详解
网络·网络协议·http
悠悠~飘1 天前
php学习(第二天)
开发语言·学习·php
zgc12453671 天前
汇编基础1
汇编·学习
qq7798233401 天前
PMP考试学习计划与知识大纲
学习·产品经理
索迪迈科技1 天前
java后端工程师进修ing(研一版‖day42)
java·开发语言·学习·算法
长安——归故李1 天前
【modbus学习】
java·c语言·c++·学习·算法·c#
索迪迈科技1 天前
STL库——map/set(类函数学习)
开发语言·c++·学习
我命由我123451 天前
Excel 表格 - Excel 减少干扰、专注于内容的查看方式
学习·ui·excel·photoshop·表格·ps·美工
我命由我123451 天前
Excel 表格 - Excel 单元格添加边框
学习·ui·excel·课程设计·photoshop·ps·美工