这是我在 android 中的 websocket 客户端。这是一个快速测试,服务器的回复应该显示在TextView
.
Boolean status1 = false;
static String msg = "reply ";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
java.lang.System.setProperty("java.net.preferIPv6Addresses", "false");
java.lang.System.setProperty("java.net.preferIPv4Stack", "true");
final TextView text = (TextView) findViewById(R.id.textView1);
final TextView text1 = (TextView) findViewById(R.id.textView2);
final Button button = (Button) findViewById(R.id.button1);
try {
final WebSocketClient client = new WebSocketClient(new URI(
"ws://10.0.2.2:8080/_024_WebSocketTest4/echo")) {
@Override
public void onOpen(ServerHandshake handshakedata) {
Log.d("1", "open");
status1 = true;
}
@Override
public void onMessage(String message) {
msg += message;
Log.d("reply", message);
print(text1);
}
@Override
public void onError(Exception ex) {
// TODO Auto-generated method stub
}
@Override
public void onClose(int code, String reason, boolean remote) {
status1 = false;
}
};
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
connect(client);
}
});
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void connect(WebSocketClient client) {
final TextView text = (TextView) findViewById(R.id.textView1);
client.connect();
while (!status1) {
}
text.setText(client.getReadyState().toString());
client.send("Hello");
//final TextView text1 = (TextView) findViewById(R.id.textView2);
//text1.setText(msg);
}
public void print(TextView text1) {
Log.d("print", msg);
text1.setText(msg);
}
当服务器发送消息时,它没有显示在文本视图中。但在 Logcat 中会显示回复。可能是什么问题呢?