[英]Spring boot WebSockets TextWebSocketHandler not working with json messges
I have added web sockets to my app for transmitting messages and make an interactive app.我在我的应用程序中添加了网络套接字以传输消息并制作一个交互式应用程序。
What I need to transmit with web-sockets is the POJO Objects.我需要用网络套接字传输的是 POJO 对象。 But, the
TextWebSocketHandler
is not working and not sending messages.但是,
TextWebSocketHandler
不起作用并且不发送消息。 When I test the web sockets, I get:当我测试网络套接字时,我得到:
WebSocket is already in CLOSING or CLOSED state.
WebSocket 已经处于 CLOSING 或 CLOSED 状态。
I don't know if it work but I think the size of the messages is stopping the web socket.我不知道它是否有效,但我认为消息的大小正在阻止网络套接字。
Code:代码:
@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.