@Configuration
public class WebSocketConfig implements ServletContextInitializer {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
servletContext.addListener(WebAppRootListener.class);
servletContext.setInitParameter("org.apache.tomcat.websocket.textBufferSize", "52428800");
servletContext.setInitParameter("org.apache.tomcat.websocket.binaryBufferSize", "52428800");
}
}
import com.tizo.biz.base.utils.AssertLog;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
@Component
@ServerEndpoint("/notice/{userId}")
public class WebSocketServer {
/**
* ConcurrentHashMap包的线程安全Map,用来存放每个客户端对应的Session对象。
*/
private static final ConcurrentHashMap<String, Session> webSocketMap = new ConcurrentHashMap<>();
/**
* 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(@PathParam("userId") String userId, Session session) throws IOException {
if (webSocketMap.containsKey(userId)) {
webSocketMap.get(userId).close();
webSocketMap.remove(userId);
}
webSocketMap.put(userId, session);
AssertLog.info(session.getRequestURI().getPath() + ",用户连接:" + userId + ",当前在线人数为:" + webSocketMap.size());
try {
sendMessage("连接成功", session);
} catch (IOException e) {
AssertLog.error("用户:" + userId + ",网络异常!!!!!!" + e.getMessage());
session.close();
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose(@PathParam("userId") String userId, Session session) {
if (webSocketMap.containsKey(userId)) {
webSocketMap.remove(userId);
}
AssertLog.info(session.getRequestURI().getPath() + ",用户退出:" + userId + ",当前在线人数为:" + webSocketMap.size());
try {
session.close();
} catch (IOException e) {
AssertLog.error("关闭连接异常:" + e.getMessage());
}
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
*/
@OnMessage
public void onMessage(@PathParam("userId") String userId, String message, Session session) {
AssertLog.info(session.getRequestURI().getPath() + ",接收用户ID:" + userId + ",接收报文:" + message);
}
/**
* 异常
*/
@OnError
public void onError(@PathParam("userId") String userId, Session session, Throwable error) {
AssertLog.error(session.getRequestURI().getPath() + ",用户错误:" + userId + ",原因:" + error.getMessage());
}
/**
* 实现服务器主动推送
*/
public void sendMessage(String message, Session session) throws IOException {
session.getAsyncRemote().sendText(message);
}
/**
* 发送自定义消息
*/
public static void sendMessage(String userId, String message) {
AssertLog.info("发送消息给:" + userId + ",发送报文:" + message);
if (StringUtils.isNotBlank(userId) && webSocketMap.containsKey(userId)) {
webSocketMap.get(userId).getAsyncRemote().sendText(message);
} else {
AssertLog.error("用户" + userId + ",不在线!");
}
}
}