我的问题是我的套接字正在发送数据但没有接收数据。我在这里粘贴代码-我哪里出错了?当我检查为Log时,显示消息正在发送,但我的套接字未接收到数据。我在这里使用默认套接字URL。
我的代码是:
public class MainActivity extends AppCompatActivity {
private Button sendBtn;
private TextView textView;
private com.github.nkzawa.socketio.client.Socket mSocket;
{
try {
mSocket = IO.socket("http://chat.socket.io");
} catch (URISyntaxException e) {}
}
private EditText mInputMessageView;
private Emitter.Listener onNewMessage = new Emitter.Listener() {
@Override
public void call(final Object... args) {
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
JSONObject data = (JSONObject) args[0];
String username;
String message;
try {
username = data.getString("username");
message = data.getString("message");
} catch (JSONException e) {
return;
}
// add the message to view
addMessage(username, message);
}
});
}
};
private void addMessage(String username, String message) {
textView.setText(username+message);
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mInputMessageView = (EditText) findViewById(R.id.mInputMessageView);
sendBtn = (Button) findViewById(R.id.sendBtn);
textView = (TextView) findViewById(R.id.textView);
mSocket.on("new message", onNewMessage);
mSocket.connect();
sendBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
attemptSend();
}
});
}
@Override
public void onDestroy() {
super.onDestroy();
mSocket.disconnect();
mSocket.off("new message", onNewMessage);
}
private void attemptSend() {
String message = mInputMessageView.getText().toString().trim();
if (TextUtils.isEmpty(message)) {
return;
}
mInputMessageView.setText("");
mSocket.emit("new message", message);
}
}