我有一个websocket服务器。我收到的消息是,收到消息后,我试图将其发送到另一个将实际处理这些消息的websocket服务器。我通过创建ClientEndpoint将消息发送到另一台服务器。我无法在客户端端点上得到任何响应。我不确定我的代码设置是否正确。请帮忙 ServerSocketHandler
public class ServerSocketHandler extends AbstractWebSocketHandler {
private Map<WebSocketSession, ProcessingService> sessions = new HashMap<>();
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
sessions.put(session, new ProcessingService());
log.info("New connection established from client, sessionId={}", session.getId());
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
sessions.get(session).send(message.getPayload());
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
sessions.get(session).close();
sessions.remove(session);
}
}
ProcessingService
@ClientEndpoint
public class ProcessingService {
private Session session = null;
private static final String SERVER_URL = "wss://serverb.com/endpoint";
public ProcessingService() {
try {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
this.session = container.connectToServer(this, URI.create(SERVER_URL));
} catch (Exception e) {
e.printStackTrace();
}
}
@OnOpen
public void onOpen(Session session) {
this.session = session;
log.info("New connection established to serverB, sessionId={}", session.getId());
}
@OnMessage
public void onMessage(String message, Session session) {
log.info(message);
}
@OnClose
public void onClose(Session session, CloseReason reason) {
this.session = null;
log.info("connection closed, sessionId={}, code={}", session.getId(), reason.getCloseCode());
}
@OnError
public void onError(Throwable t) {
t.printStackTrace();
}
public void send(String message) throws Exception {
this.session.getBasicRemote().sendText(message);
}
public void close() throws Exception {
this.session.getAsyncRemote().sendBinary(ByteBuffer.wrap(new byte[0]));
}