I'm trying to implement a WebSocket client.
My code is here:
import org.json.JSONObject;
import javax.websocket.*;
import java.io.IOException;
public class MyClientEndpoint extends Endpoint {
private Session session;
@Override
public void onOpen(Session session, EndpointConfig endpointConfig) {
System.out.println("Web socket opened");
this.session = session;
this.session.addMessageHandler(new MessageHandler.Whole<String>() {
public void onMessage(String message) {
System.out.println("!!!!!!!!!!!!!!! Retrieved: " + message);
JSONObject jsonResponse = new JSONObject(message);
String user = jsonResponse.get("user").toString();
System.out.println("!!!!!!!!!!!!!!! The User: " + user);
}
});
}
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
}
The problem comes in onMessage(String message)
method, because after the message is printed it seems that I can not process the message in order to create the String user
object. How I can implement this?
I am using Glassfish Tyrus.
Thank you!
I've found where the problem was. In JSONObject
that I've created, the user
key is not on the first row, so I must take another key in order to have access to the user
key. The problem is that when I try to access the user
key I'm not receiveing any exception.