【问题标题】:Spring boot WebSockets TextWebSocketHandler not working with json messgesSpringboot WebSocket TextWebSocketHandler 不适用于 json 消息
【发布时间】:2017-04-24 12:04:38
【问题描述】:

我在我的应用程序中添加了网络套接字,用于传输消息并制作交互式应用程序。

我需要使用网络套接字传输的是 POJO 对象。但是,TextWebSocketHandler 不工作并且不发送消息。当我测试网络套接字时,我得到:

WebSocket 已经处于 CLOSING 或 CLOSED 状态。

我不知道它是否有效,但我认为消息的大小正在阻止网络套接字。

代码:

@Configuration
@EnableWebSocket
public class WebsocketConfig implements WebSocketConfigurer{
    @Bean
    public WebSocketHandler myMessageHandler() {
        return new MyMessageHandler();
    }


    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(myMessageHandler(), "/my-websocket-endpoint");
    }

}

public class MyMessageHandler extends TextWebSocketHandler {

    @Autowired
    UserRepository userRepository;

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // The WebSocket has been closed
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // The WebSocket has been opened
        // I might save this session object so that I can send messages to it outside of this method

        // Let's send the first message
        Gson gson=new Gson();
        session.sendMessage(new TextMessage(gson.toJson(findall())));
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage textMessage) throws Exception {
        // A message has been received

            Gson gson=new Gson();
            session.sendMessage(new TextMessage(gson.toJson(findall())));

    }

    public List<User> findall(){

        return userRepository.findAll();

    }

}

【问题讨论】:

    标签: java spring-boot websocket


    【解决方案1】:

    尝试在使用 json 解析的方法中删除 throws Exception,然后在解析操作周围应用 try 和 catch 并处理您可能遇到的异常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-20
      • 1970-01-01
      • 2020-10-13
      • 1970-01-01
      • 1970-01-01
      • 2015-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多