[英]Message handling in onMessage WebSocket
I'm trying to implement a WebSocket client. 我正在尝试实现WebSocket客户端。
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. 该问题来自
onMessage(String message)
方法,因为在打印消息后,似乎无法处理该消息以创建String user
对象。 How I can implement this? 我该如何实施?
I am using Glassfish Tyrus. 我正在使用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. 在我创建的
JSONObject
中, user
密钥不在第一行,因此我必须使用另一个密钥才能访问该user
密钥。 The problem is that when I try to access the user
key I'm not receiveing any exception. 问题是,当我尝试访问
user
密钥时,没有收到任何异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.