我在实现Android socket.io客户端时遇到问题。基本上,我有一个Angular Web应用程序和一个Android应用程序,应该使用套接字服务器相互通信。这是用于处理套接字的Android代码:
private Socket mSocket;
private String mRoomId;
private int mClientId = -1;
private int mReceiverId = -1;
private Emitter.Listener mMessageListener = args -> {
JSONObject data = (JSONObject) args[0];
Log.i(TAG, "Message: " + data.toString());
try {
RTCMessage message = new RTCMessage(data);
if(mClientId == message.receiver()) {
// Message was sent to this client
handleSignalingMessage(message);
}
} catch (JSONException ex) {
ex.printStackTrace(); // TODO Handle
if(mListener != null) mListener.onChannelError(ex.getLocalizedMessage());
}
};
private Emitter.Listener mPeerConnectedListener = args -> {
JSONObject data = (JSONObject) args[0];
Log.i(TAG, "Peer connected: " + data.toString());
try {
if (data.has("id")) {
mReceiverId = data.getInt("id");
if(mListener != null) {
mListener.onRemoteConnected(mReceiverId);
}
} else {
// Connection without receiver id, this is an error
}
} catch (JSONException ex) {
ex.printStackTrace(); // TODO Handle
if(mListener != null) mListener.onChannelError(ex.getLocalizedMessage());
}
};
private Emitter.Listener mPeerDisconnectedListener = args -> {
JSONObject data = (JSONObject) args[0];
Log.i(TAG, "Peer disconnected: " + data.toString());
mReceiverId = -1;
};
public void setListener(@NonNull RTCClient.SignalingEvents listener) {
this.mListener = listener;
}
public void connect(String url) {
try {
Log.i(TAG, "Connecting to WebSocket");
IO.Options opts = new IO.Options();
opts.forceNew = false;
mSocket = IO.socket(url, opts);
// Must be called AFTER bindEvents
mSocket.connect();
bindEvents(mSocket);
createRoom();
} catch (URISyntaxException e) {
e.printStackTrace(); // TODO Handle
}
}
public void disconnect() {
if(mSocket != null) {
Log.i(TAG, "Disconnecting from WebSocket");
mSocket.disconnect();
} else {
Log.d(TAG, "Tried to close uninitialized socket");
}
}
private void bindEvents(Socket socket) {
Log.i(TAG, "Binding socket events");
socket.on(Socket.EVENT_CONNECT, args -> {
Log.i(TAG, "Connected to socket");
});
socket.on("msg", mMessageListener);
socket.on("peer.connected", mPeerConnectedListener);
socket.on("peer.disconnected", mPeerDisconnectedListener);
}
我会注意到,经过一些研究,似乎Web应用程序正确发送了消息,并且两者都成功加入了同一个会议室。套接字服务器还成功转发了“ peer.connected”消息,但Android客户端不处理它(以及“ msg”和“ peer.disconnected”消息,但它确实正确接收了Socket.EVENT_CONNECT
消息)< / p>