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

}
复制代码
相关推荐
小武~4 分钟前
嵌入式网络编程深度优化 --网络协议栈配置实战指南
linux·网络·网络协议
kblj555525 分钟前
学习Linux——网络——网卡
linux·网络·学习
暖阳之下26 分钟前
学习周报二十
人工智能·深度学习·学习
charlie1145141911 小时前
CSS学习笔记3:颜色、字体与文本属性基础
css·笔记·学习·教程·基础
wangqiaowq2 小时前
PAIMON+STARROCKS 学习
学习
phoenix09812 小时前
ELK企业级日志分析系统学习
学习·elk
奋斗的牛马2 小时前
FPGA—ZYNQ学习GPIO-EMIO,MIO,AXIGPIO(五)
单片机·嵌入式硬件·学习·fpga开发·信息与通信
拾忆,想起2 小时前
TCP粘包拆包全解析:数据流中的“藕断丝连”与“一刀两断”
java·网络·数据库·网络协议·tcp/ip·哈希算法
ACGkaka_3 小时前
设计模式学习(十二)状态模式
学习·设计模式·状态模式
TheInk3 小时前
python学习笔记之Python基础教程(crossin全60课)
笔记·python·学习