我使用Spring实现了以下Web-Socket服务器。我们不想使用STOMP和JSocks。
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new WebSocketServerHandler(), "/websocket/user/{userId}");
}
}
@Service
public class WebSocketServerHandler extends TextWebSocketHandler {
private List<WebSocketSession> sessions = new ArrayList<WebSocketSession>();
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message)
throws Exception {
session.sendMessage(message);
}
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
sessions.add(session);
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
sessions = null;
}
}
现在,我可以成功地从前端客户端(浏览器)连接到Web-Socket服务器。现在,我想在运行时从我的一些Java类中连接到Web-Socket服务器,然后想向该Web-Socket服务器发送消息。有人知道我该如何实现吗?
我已经添加了一个测试Rest Controller,如下所示:
@RequestMapping(value = "/web-socket/message/{message}")
public void sendMessage(@PathVariable("message") final String message) throws Exception {
final String WS_URI = "ws://localhost:8080/web-socket/user/23";
final CountDownLatch latch = new CountDownLatch(1);
WebSocketClientHandler handler = new WebSocketClientHandler(latch);
WebSocketClient client = new StandardWebSocketClient();
WebSocketSession session = client.doHandshake(handler, WS_URI).get();
session.sendMessage(new TextMessage(message));
latch.await(5, TimeUnit.SECONDS);
session.close();
我能够成功地通过调用Google Rest客户端并使用此测试RestController向WebSocket服务器发送消息,但仅限于第一次。如果我需要再次发送消息,则必须重新启动Tomcat服务器。这里是否有任何问题?