[英]Spring boot WebSockets TextWebSocketHandler not working with json messges
我在我的應用程序中添加了網絡套接字以傳輸消息並制作一個交互式應用程序。
我需要用網絡套接字傳輸的是 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();
}
}
嘗試在使用 json 解析的方法中刪除 throws Exception,然后在解析操作中應用 try 和 catch 並處理您可能遇到的異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.