xxdezh hai 7 meses
pai
achega
9a167e120d

+ 1 - 1
pom.xml

@@ -444,7 +444,7 @@
                     <includeSystemScope>true</includeSystemScope>
                     <!-- 关键新增:指定唯一主类(二选一,根据你的实际入口选择) -->
                     <mainClass>com.sqx.SqxApplication</mainClass>
-                    <!-- 若要使用 WebSocketApp 作为入口,替换为:<mainClass>com.sqx.WebSocketApp</mainClass> -->
+                    <!-- 若要使用 WebSocketApp 作为入口,替换为:<mainClass>com.sqx.WebSocketApp</mainClass>  SqxApplication -->
                 </configuration>
             </plugin>
             <!-- 跳过单元测试 -->

+ 3 - 0
src/main/java/com/sqx/SqxApplication.java

@@ -1,11 +1,13 @@
 package com.sqx;
 
+import com.sqx.config.WebSocketConfig;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
 import org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration;
 import org.springframework.cache.annotation.EnableCaching;
+import org.springframework.context.annotation.Import;
 import org.springframework.scheduling.annotation.EnableScheduling;
 
 
@@ -13,6 +15,7 @@ import org.springframework.scheduling.annotation.EnableScheduling;
 @EnableScheduling
 @EnableCaching
 @SpringBootApplication
+@Import(WebSocketConfig.class)
 public class SqxApplication {
 
 	public static void main(String[] args) {

+ 6 - 0
src/main/java/com/sqx/common/MyWebSocketHandler.java

@@ -37,4 +37,10 @@ public class MyWebSocketHandler extends TextWebSocketHandler {
         sessions.remove(session);
         System.out.println("连接关闭,当前在线:" + sessions.size());
     }
+
+    @Override
+    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
+        System.err.println("WebSocket 传输错误:" + exception.getMessage());
+        exception.printStackTrace();
+    }
 }

+ 3 - 5
src/main/java/com/sqx/config/WebSocketConfig.java

@@ -7,15 +7,13 @@ import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
 import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
 
 @Configuration
-@EnableWebSocket // 启用WebSocket支持
+@EnableWebSocket // 启用Spring WebSocket支持
 public class WebSocketConfig implements WebSocketConfigurer {
 
     @Override
     public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
-        // 注册端点:客户端通过ws://ip:port/ws连接
-        // setAllowedOrigins("*")允许跨域(生产环境需限制来源)
+        // 注册Spring WebSocket处理器,端点为/ws
         registry.addHandler(new MyWebSocketHandler(), "/ws")
-                .setAllowedOriginPatterns("*");
-        // .setAllowedOrigins("*");
+                .setAllowedOriginPatterns("*"); // 允许跨域(生产环境需限制)
     }
 }

+ 43 - 47
src/main/java/com/sqx/modules/chat/controller/app/AppChatSocket.java

@@ -23,8 +23,8 @@ import java.util.concurrent.ConcurrentHashMap;
 
 @Slf4j
 @Component
-@ServerEndpoint("/sqx_fast/chatSocket/{userId}")
-public class AppChatSocket {//用户聊天
+@ServerEndpoint("/chatSocket/{userId}")
+public class AppChatSocket {// 用户聊天
 
     /**
      * 在线人数
@@ -34,7 +34,7 @@ public class AppChatSocket {//用户聊天
      * 以用户的id为key,WebSocket为对象保存起来
      */
     private static Map<String, AppChatSocket> clients = new ConcurrentHashMap<String, AppChatSocket>();
-    private static SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     /**
      * 会话
      */
@@ -50,55 +50,51 @@ public class AppChatSocket {//用户聊天
 
     // 注入的时候,给类的 service 注入
     @Autowired
-    public void setWxChatContentService(ChatContentService chatContentService,UserService userService) {
+    public void setWxChatContentService(ChatContentService chatContentService, UserService userService) {
         AppChatSocket.chatContentService = chatContentService;
         AppChatSocket.userService = userService;
     }
 
-
-
     /**
      * 建立连接
      *
      * @param session
      */
     @OnOpen
-    public void onOpen(@PathParam("userId") String userId, Session session)
-    {
+    public void onOpen(@PathParam("userId") String userId, Session session) {
         onlineNumber++;
-        log.info("现在来连接的客户id:"+userId);
+        log.info("现在来连接的客户id:" + userId);
         this.userId = userId;
         this.session = session;
         log.info("有新连接加入! 当前在线人数" + onlineNumber);
         try {
-            //把自己的信息加入到map当中去
+            // 把自己的信息加入到map当中去
             AppChatSocket appChatSocket = clients.get(userId);
-            if(appChatSocket!=null){
+            if (appChatSocket != null) {
                 clients.remove(userId);
             }
             clients.put(userId, this);
 
-            /*sendMessageTo("恭喜你连接成功!",wxUserId);*/
-        }
-        catch (Exception e){
-            log.error(userId+"上线的时候通知所有人发生了错误");
+            /* sendMessageTo("恭喜你连接成功!",wxUserId); */
+        } catch (Exception e) {
+            log.error(userId + "上线的时候通知所有人发生了错误");
         }
 
     }
 
     @OnError
     public void onError(Session session, Throwable error) {
-        log.error("服务端发生了错误"+error.getMessage());
-        //error.printStackTrace();
+        log.error("服务端发生了错误" + error.getMessage());
+        // error.printStackTrace();
     }
+
     /**
      * 连接关闭
      */
     @OnClose
-    public void onClose()
-    {
+    public void onClose() {
         onlineNumber--;
-        //webSockets.remove(this);
+        // webSockets.remove(this);
         clients.remove(userId);
         log.info("有连接关闭! 当前在线人数" + onlineNumber);
     }
@@ -110,8 +106,7 @@ public class AppChatSocket {//用户聊天
      * @param session 会话
      */
     @OnMessage
-    public void onMessage(String message, Session session)
-    {
+    public void onMessage(String message, Session session) {
 
         if (Objects.equals("HeartBeat", message)) {
             return;
@@ -125,15 +120,16 @@ public class AppChatSocket {//用户聊天
             String height = jsonObject.getString("height");
             String userId = jsonObject.getString("userId");
             String chatConversationId = jsonObject.getString("chatConversationId");
-            chatContentService.updateChatContentStatusByUserIdAndChatId(Long.parseLong(this.userId), Long.parseLong(chatConversationId));
-            if("24".equals(messageType)){
+            chatContentService.updateChatContentStatusByUserIdAndChatId(Long.parseLong(this.userId),
+                    Long.parseLong(chatConversationId));
+            if ("24".equals(messageType)) {
                 AppChatSocket chatSocket = clients.get(userId);
-                if (chatSocket!=null) {
+                if (chatSocket != null) {
                     chatSocket.session.getAsyncRemote().sendText(message);
                 }
-            }else{
-                //将聊天记录保存包数据库中
-                ChatContent wxChatContent=new ChatContent();
+            } else {
+                // 将聊天记录保存包数据库中
+                ChatContent wxChatContent = new ChatContent();
                 wxChatContent.setChatConversationId(Long.parseLong(chatConversationId));
                 wxChatContent.setUserId(Long.parseLong(this.userId));
                 wxChatContent.setWidth(width);
@@ -141,48 +137,48 @@ public class AppChatSocket {//用户聊天
                 wxChatContent.setContent(textMessage);
                 wxChatContent.setMessageType(messageType);
                 wxChatContent.setCreateTime(sdf.format(new Date()));
-                //判断对方是否在线
+                // 判断对方是否在线
                 AppChatSocket chatSocket = clients.get(userId);
-                if (chatSocket!=null) {
+                if (chatSocket != null) {
                     chatSocket.session.getAsyncRemote().sendText(message);
                 }
                 wxChatContent.setStatus(0);
                 chatContentService.save(wxChatContent);
                 UserEntity userEntity = userService.selectUserById(Long.parseLong(userId));
-                if(userEntity!=null && StringUtils.isNotBlank(userEntity.getClientid())){
+                if (userEntity != null && StringUtils.isNotBlank(userEntity.getClientid())) {
                     UserEntity user = userService.selectUserById(Long.parseLong(this.userId));
-                    if("2".equals(messageType)){
-                        textMessage="[图片]";
-                    }else if("3".equals(messageType)){
-                        textMessage="[语音]";
+                    if ("2".equals(messageType)) {
+                        textMessage = "[图片]";
+                    } else if ("3".equals(messageType)) {
+                        textMessage = "[语音]";
                     }
-                    userService.pushToSingle("新消息提醒",user.getUserName()+":"+textMessage,userEntity.getClientid());
+                    userService.pushToSingle("新消息提醒", user.getUserName() + ":" + textMessage, userEntity.getClientid());
                 }
             }
 
-            /*AppChatSocket chatSocket = clients.get(userId);
-            if (chatSocket!=null) {
-                chatSocket.session.getAsyncRemote().sendText(message);
-            }*/
-        }
-        catch (Exception e){
-            log.error("发生了错误了"+e.getMessage(),e);
+            /*
+             * AppChatSocket chatSocket = clients.get(userId);
+             * if (chatSocket!=null) {
+             * chatSocket.session.getAsyncRemote().sendText(message);
+             * }
+             */
+        } catch (Exception e) {
+            log.error("发生了错误了" + e.getMessage(), e);
         }
 
     }
 
-
     public void sendMessageTo(String message, String ToUserName) throws IOException {
         for (AppChatSocket item : clients.values()) {
-            if (item.userId.equals(ToUserName) ) {
+            if (item.userId.equals(ToUserName)) {
                 item.session.getAsyncRemote().sendText(message);
-                System.err.println(this.userId+"发送成功:"+ToUserName);
+                System.err.println(this.userId + "发送成功:" + ToUserName);
                 break;
             }
         }
     }
 
-    public void sendMessageAll(String message,String FromUserName) throws IOException {
+    public void sendMessageAll(String message, String FromUserName) throws IOException {
         for (AppChatSocket item : clients.values()) {
             item.session.getAsyncRemote().sendText(message);
         }