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

}
复制代码
相关推荐
weixin_455446174 分钟前
Python学习的主要知识框架
开发语言·python·学习
城南云小白3 小时前
web基础+http协议+httpd详细配置
前端·网络协议·http
Ylucius3 小时前
动态语言? 静态语言? ------区别何在?java,js,c,c++,python分给是静态or动态语言?
java·c语言·javascript·c++·python·学习
LvManBa3 小时前
Vue学习记录之六(组件实战及BEM框架了解)
vue.js·学习·rust
LvManBa3 小时前
Vue学习记录之三(ref全家桶)
javascript·vue.js·学习
Tony聊跨境3 小时前
什么是 SSL 代理?
网络·网络协议·ssl
知识分享小能手4 小时前
mysql学习教程,从入门到精通,SQL DISTINCT 子句 (16)
大数据·开发语言·sql·学习·mysql·数据分析·数据库开发
汀、人工智能5 小时前
报错error: RPC failed,curl 16 Error in the HTTP2 framing layer解决方法
网络·git·网络协议·rpc
晓幂5 小时前
CTFShow-信息搜集
笔记·学习