<!DOCTYPE html>
<html>
<head>
<title>WebSocket Example</title>
<script>
let socket = new WebSocket("http://localhost:8081/api/websocket/{userid}");
let heartbeatInterval;
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);
}
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>
</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);
}
}