|
@@ -0,0 +1,67 @@
|
|
|
+package thyyxxk.wxservice_server.websocket;
|
|
|
+
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
+import org.springframework.stereotype.Component;
|
|
|
+
|
|
|
+import javax.websocket.*;
|
|
|
+import javax.websocket.server.PathParam;
|
|
|
+import javax.websocket.server.ServerEndpoint;
|
|
|
+import java.util.concurrent.ConcurrentHashMap;
|
|
|
+import java.util.concurrent.atomic.AtomicInteger;
|
|
|
+
|
|
|
+/**
|
|
|
+ * @description: websoket config
|
|
|
+ * @author: DingJie
|
|
|
+ * @create: 2021-05-18 11:20:43
|
|
|
+ **/
|
|
|
+@Slf4j
|
|
|
+@ServerEndpoint("/websocket/{openId}")
|
|
|
+@Component
|
|
|
+public class WebSocketServer {
|
|
|
+ private static final AtomicInteger ONLINE_COUNT = new AtomicInteger();
|
|
|
+ private static final ConcurrentHashMap<String, Session> SESSION_MAP = new ConcurrentHashMap<>();
|
|
|
+
|
|
|
+ @OnOpen
|
|
|
+ public void onOpen(Session session, @PathParam("openId") String openId) {
|
|
|
+ SESSION_MAP.put(openId, session);
|
|
|
+ ONLINE_COUNT.incrementAndGet();
|
|
|
+ log.info("有新连接加入:{},当前在线人数为:{}", openId, ONLINE_COUNT.get());
|
|
|
+ }
|
|
|
+
|
|
|
+ @OnClose
|
|
|
+ public void onClose(@PathParam("openId") String openId) {
|
|
|
+ SESSION_MAP.remove(openId);
|
|
|
+ ONLINE_COUNT.decrementAndGet();
|
|
|
+ log.info("有一连接关闭:{},当前在线人数为:{}", openId, ONLINE_COUNT.get());
|
|
|
+ }
|
|
|
+
|
|
|
+ @OnMessage
|
|
|
+ public void onMessage(String message) {
|
|
|
+ log.info("收到信息:{}", message);
|
|
|
+ }
|
|
|
+
|
|
|
+ @OnError
|
|
|
+ public void onError(Session session, Throwable error) {
|
|
|
+ error.printStackTrace();
|
|
|
+ log.error("发生错误>>> session: {},错误:{} ", session.getId(), error.getMessage());
|
|
|
+ }
|
|
|
+
|
|
|
+ public static void sendMessage(String openId, String message) {
|
|
|
+ Session session = SESSION_MAP.get(openId);
|
|
|
+ if (null == session) {
|
|
|
+ log.info("用户不在线,无法发送消息。【openId: {},message: {}】", openId, message);
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ try {
|
|
|
+ session.getBasicRemote().sendText(message);
|
|
|
+ log.info("发送消息成功。【openId: {},message: {}】", openId, message);
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.error("发送socket消息出错。【openId: {},message: {}, exception: {}】", openId, message, e.getMessage());
|
|
|
+ e.printStackTrace();
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ public static int getOnlineCount() {
|
|
|
+ return ONLINE_COUNT.get();
|
|
|
+ }
|
|
|
+}
|