websocket学习

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

}


相关推荐

  1. 学习websocket

    2024-07-12 04:16:05       37 阅读
  2. websocket学习

    2024-07-12 04:16:05       27 阅读
  3. netty websocket学习

    2024-07-12 04:16:05       64 阅读
  4. WebSocket学习笔记

    2024-07-12 04:16:05       28 阅读
  5. 十分钟学会WebSocket

    2024-07-12 04:16:05       48 阅读
  6. 十分钟学会WebSocket

    2024-07-12 04:16:05       32 阅读
  7. WebSocket

    2024-07-12 04:16:05       58 阅读
  8. websocket

    2024-07-12 04:16:05       48 阅读
  9. WebSocket

    2024-07-12 04:16:05       58 阅读
  10. <span style='color:red;'>WebSocket</span>

    WebSocket

    2024-07-12 04:16:05      41 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-12 04:16:05       66 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-12 04:16:05       70 阅读
  3. 在Django里面运行非项目文件

    2024-07-12 04:16:05       57 阅读
  4. Python语言-面向对象

    2024-07-12 04:16:05       68 阅读

热门阅读

  1. Docker 安装字体文件

    2024-07-12 04:16:05       28 阅读
  2. 玩转springboot之xxxRunner接口使用

    2024-07-12 04:16:05       24 阅读
  3. Spring Security的Filter

    2024-07-12 04:16:05       27 阅读
  4. WVP后端项目文件结构

    2024-07-12 04:16:05       30 阅读
  5. 贪心算法-以学籍管理系统为例

    2024-07-12 04:16:05       26 阅读
  6. RISC-V主要指令集介绍及规则

    2024-07-12 04:16:05       27 阅读
  7. 【ChatGPT】全面解析 ChatGPT:从起源到未来

    2024-07-12 04:16:05       21 阅读
  8. 代码随想录算法训练营第9天

    2024-07-12 04:16:05       25 阅读
  9. 担心插座预留的不够用,家里装修留多少开关插座

    2024-07-12 04:16:05       19 阅读