I have used this code to write the websocket client in java. It's a secure socket. Connection to destination is established fine but onMessage is not getting called.
When I write the same thing in java script it's working and able to get response.
Please check my code and advise what am I missing here.
My Code:
@ClientEndpoint
public class MyClientEndpoint {
@SuppressWarnings("unchecked")
@OnOpen
public void onOpen(Session session) {
System.out.println("Connected to endpoint: " + session.getBasicRemote());
try {
JSONObject obj = new JSONObject();
obj.put("subscribe", URLEncoder.encode("xxxxxxx","UTF-8"));
String msg = obj.toJSONString();
System.out.println("Sending message to endpoint: " + msg);
session.getBasicRemote().sendText(msg);
} catch (Exception ex) {
Logger.getLogger(MyClientEndpoint.class.getName()).log(Level.SEVERE, null, ex);
}
}
@OnMessage
public void onMessage(String message) {
System.out.println("Received message in client: " + message);
Client.messageLatch.countDown();
}
public class Client {
final static CountDownLatch messageLatch = new CountDownLatch(1);
public static void main(String[] args) {
try {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
String uri = "wss://api.....";
System.out.println("Connecting to:: " + uri);
container.connectToServer(MyClientEndpoint.class, URI.create(uri));
messageLatch.await(10, TimeUnit.SECONDS);
} catch (DeploymentException | InterruptedException | IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I am able to connect to secure websocket by passing credentials in
ClientEndpointConfig.Configurator configurator = new ClientEndpointConfig.Configurator() {
public void beforeRequest(Map<String, List<String>> headers) {
String credentials = "username:password";
headers.put("Authorization", Arrays.asList("Basic " + new BASE64Encoder().encode(credentials.getBytes())));
System.out.println("Header set successfully");
}
};
ClientEndpointConfig clientConfig = ClientEndpointConfig.Builder.create()
.configurator(configurator)
.build();
I documented the steps in the below link.
https://bigdatatechbytes.blogspot.in/2017/10/java-client-for-secure-web-socket.html