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

}
复制代码
相关推荐
光影少年3 小时前
angular生态及学习路线
前端·学习·angular.js
猫头虎5 小时前
如何查看局域网内IP冲突问题?如何查看局域网IP环绕问题?arp -a命令如何使用?
网络·python·网络协议·tcp/ip·开源·pandas·pip
逆小舟7 小时前
【C/C++】指针
c语言·c++·笔记·学习
武文斌778 小时前
项目学习总结:LVGL图形参数动态变化、开发板的GDB调试、sqlite3移植、MQTT协议、心跳包
linux·开发语言·网络·arm开发·数据库·嵌入式硬件·学习
递归不收敛8 小时前
吴恩达机器学习课程(PyTorch适配)学习笔记:1.3 特征工程与模型优化
pytorch·学习·机器学习
爱吃小胖橘8 小时前
Unity网络开发--超文本传输协议Http(1)
开发语言·网络·网络协议·http·c#·游戏引擎
kunge1v58 小时前
学习爬虫第四天:多任务爬虫
爬虫·python·学习·beautifulsoup
哲Zheᗜe༘8 小时前
了解学习MySQL数据库基础
数据库·学习·mysql
peter676810 小时前
pandas学习小结
学习·pandas
机器视觉知识推荐、就业指导10 小时前
STM32 外设驱动模块【含代码】:SG90 舵机模块
stm32·单片机·嵌入式硬件·学习