You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

80 lines
2.5 KiB
Java

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package com.ipsplm.websocket;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
/**
* @Description WebSocket处理类
* @Author FanDongqiang
* @Date 2023/5/8 9:17
* @Version 1.0
*/
@Component
@Slf4j
@ServerEndpoint("/websocket/test-token4")
public class WebSocketHandler4 {
private static ConcurrentHashMap<String, WebSocketHandler4> webSocketMap = new ConcurrentHashMap<>();
private final ReentrantLock reentrantLock = new ReentrantLock();
private Session session;
@OnOpen
public void handleOpen(Session session, @PathParam("token") String token) {
this.session = session;
// if (StringUtils.isEmpty(token)) {
// sendInfo("[websocket ERROR] 客户端Token错误连接失败");
// }
webSocketMap.put(session.getId(), this);
log.info("[websocket]客户端创建连接session ID = {} ", session.getId());
log.info("webSocketMap内容" + webSocketMap);
}
@OnClose
public void handleClose(Session session) {
if (webSocketMap.containsKey(session.getId())) {
webSocketMap.remove(session.getId());
}
log.info("[websocket]客户端断开websocket连接session ID = {} ", session.getId());
}
@OnError
public void handleError(Session session, Throwable throwable) {
log.info("[websocket]出现错误session ID = {} ", session.getId());
log.info("[websocket]出现错误throwable = {} ", throwable);
}
// 发送数据到客户端
public static void sendInfo(String message) {
for (String item : webSocketMap.keySet()) {
webSocketMap.get(item).sendMessage(message);
}
}
public void sendMessage(String message) {
try {
//加锁
reentrantLock.lock();
if (this.session != null && this.session.isOpen()) {
this.session.getBasicRemote().sendText(message);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//解锁
reentrantLock.unlock();
}
}
}