Hello members,
Requirement
We need to connect to Websocket to establish conversation with a third-party chatbot.
Challenges: We couldn't find any reference document on the community on establishing Websocket connection.
Possible Solution : We are using javax.websocket API to connect to Websocket. We have created one ClientEndPoint to create the Websocket connection, then we are sending the query to Websocket.
Problem: Although we are able to establish the Websocket connection, we are unable to receive messages back from Websocket. The "onMessage" method should be called by Websocket and the response should be captured.
Method to create Websocket connection:
public WebSocketClientEndpoint(URI endpointURI, String auth, String sessionId) {
try {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
ClientEndpointConfig.Configurator configurator = new ClientEndpointConfig.Configurator() {
@Override
public void beforeRequest(Map<String, List<String>> headers) {
// Adding required headers, passing the auth and Session ID
}
};
ClientEndpointConfig config = ClientEndpointConfig.Builder.create().configurator(configurator).build();
container.setDefaultMaxSessionIdleTimeout(120 * 60 * 1000);
container.connectToServer(this, config, endpointURI);
} catch (Exception e) {
// handle exception
}
}
On successful connection below method will be called.
@Override
public void onOpen(Session session, EndpointConfig endpointConfig) {
// sysout("Websocket connection established successfully");
this.userSession = session;
}
We are sending query like this to the Websocket,
@Override
public synchronized void sendBinaryMessage(byte[] message) throws IOException {
if (this.userSession.isOpen()) {
RemoteEndpoint.Basic basicRemote = this.userSession.getBasicRemote();
basicRemote.sendBinary(ByteBuffer.wrap(message));
}
}
We are not receiving the response back on below method,
@OnMessage
public void onMessage(byte[] message) {
}
Although the connection is established successfully, but we are not getting the response back on the "onMessage" method for some reason. We are also not getting any error response from the Websocket. Are we missing anything on the approach? Any guidance on this would be really helpful.
The two maven dependencies which we have used are below,
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>9.0.41</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-websocket</artifactId>
<version>9.0.41</version>
</dependency>