|
|
@@ -0,0 +1,82 @@
|
|
|
+package vip.xiaonuo.dev.core.websocket;
|
|
|
+
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
+import org.springframework.context.annotation.Configuration;
|
|
|
+import org.springframework.stereotype.Component;
|
|
|
+
|
|
|
+import javax.websocket.*;
|
|
|
+import javax.websocket.server.PathParam;
|
|
|
+import javax.websocket.server.ServerEndpoint;
|
|
|
+import java.io.IOException;
|
|
|
+import java.util.Map;
|
|
|
+import java.util.concurrent.ConcurrentHashMap;
|
|
|
+import java.util.concurrent.atomic.AtomicInteger;
|
|
|
+
|
|
|
+/**
|
|
|
+ * @Author ZSS
|
|
|
+ * @Date 2024-05-28 08:39
|
|
|
+ * @Note: WebSocketServer
|
|
|
+ **/
|
|
|
+@ServerEndpoint("/webSocket/{clientId}")
|
|
|
+@Component
|
|
|
+@Slf4j
|
|
|
+public class WebSocketServer {
|
|
|
+
|
|
|
+ private static final AtomicInteger ONLINE_COUNT = new AtomicInteger(0);
|
|
|
+ private static Map<String, WebSocketServer> clients = new ConcurrentHashMap<>();
|
|
|
+ private Session session;
|
|
|
+ private String clientId;
|
|
|
+
|
|
|
+ @OnOpen
|
|
|
+ public void onOpen(@PathParam("clientId") String clientId, Session session) throws IOException {
|
|
|
+ this.clientId = clientId;
|
|
|
+ this.session = session;
|
|
|
+
|
|
|
+ clients.put(clientId, this);
|
|
|
+ // 在线数加1
|
|
|
+ int cnt = ONLINE_COUNT.incrementAndGet();
|
|
|
+ log.info("{}加入连接,当前连接数为:{}", clientId, cnt);
|
|
|
+
|
|
|
+ }
|
|
|
+
|
|
|
+ @OnClose
|
|
|
+ public void onClose() throws IOException {
|
|
|
+ clients.remove(clientId);
|
|
|
+ int cnt = ONLINE_COUNT.decrementAndGet();
|
|
|
+ log.info("有连接关闭,当前连接数为:{}", cnt);
|
|
|
+ }
|
|
|
+
|
|
|
+ @OnMessage
|
|
|
+ public void onMessage(String message) throws IOException {
|
|
|
+ log.info("来自客户端的消息:{}", message);
|
|
|
+ sendInfo(session, message);
|
|
|
+ }
|
|
|
+
|
|
|
+ @OnError
|
|
|
+ public void onError(Session session, Throwable error) {
|
|
|
+ error.printStackTrace();
|
|
|
+ }
|
|
|
+
|
|
|
+ public void sendMessage(String message, String clientId) throws Exception {
|
|
|
+ Session session = null;
|
|
|
+ for (WebSocketServer item : clients.values()) {
|
|
|
+ if (item.clientId.equals(clientId)) {
|
|
|
+ session = item.session;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if (session == null) {
|
|
|
+ throw new Exception("找不到对应的seesion!");
|
|
|
+ }
|
|
|
+ sendInfo(session, message);
|
|
|
+ }
|
|
|
+
|
|
|
+ public void sendMessageAll(String message) throws IOException {
|
|
|
+ for (WebSocketServer item : clients.values()) {
|
|
|
+ sendInfo(item.session, message);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private void sendInfo(Session session, String message) throws IOException {
|
|
|
+ session.getAsyncRemote().sendText(message);
|
|
|
+ }
|
|
|
+}
|