#websocket #spring-websocket
Вопрос:
Запустите сервер spring WebSocket с
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new WebSocketHandler() {
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
System.out.println("SERVER Established " session.getId());
}
@Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
System.out.println("SERVER Closed " session.getId());
}
@Override
public boolean supportsPartialMessages() {
return false;
}
}, "/ws").setAllowedOrigins("*");
}
}
Затем подключитесь к серверу WebSocket с помощью
@Value("${server.port}")
int port;
@Test
public void test() throws InterruptedException, IOException, ExecutionException {
URI uri = UriComponentsBuilder
.fromUriString("ws://127.0.0.1:" port "/ws").buildAndExpand().encode().toUri();
WebSocketHttpHeaders headers = new WebSocketHttpHeaders();
WebSocketSession session = new StandardWebSocketClient()
.doHandshake(new WebSocketHandler() {
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
System.out.println("CLIENT Established " session.getId());
}
@Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
System.out.println("CLIENT Closed " session.getId());
}
@Override
public boolean supportsPartialMessages() {
return false;
}
}, headers, uri)
.get();
}
Консоль, выведенная наружу, — это
SERVER Established d1d1c7ba-eecc-1a42-ad1f-ff469a4ace94
CLIENT Established ca0d6a93-49eb-5022-630b-3a06afc25200
CLIENT Closed ca0d6a93-49eb-5022-630b-3a06afc25200
SERVER Closed d1d1c7ba-eecc-1a42-ad1f-ff469a4ace94
Why are the IDs different?
What I want to do is,
-
- client : make a session and get session ID
-
- client : request a task to task server with session ID.
-
- server : listen to the session status then if
1)
session closed, request task cancelation to the task server with session ID got from3)
.
- server : listen to the session status then if
So I need to get same ID across websocket server and client.