Reputation: 180
I have connected an Android Client to a node.js server using socket.io and i am able to send messages to the server but not receive on the client. For the client side i do somthing like
Log.i("MainActivity: ", "sending message");
final JSONObject sdpObj = new JSONObject();
try {
sdpObj.put("id","presenter");
sdpObj.put("sdpOffer",localSdpOffer.description);
} catch (JSONException e) {
e.printStackTrace();
}
LoginActivity.mSocket.emit("new message", sdpObj);
and on the server i receive the object like:
io.sockets.on('connection',function(socket){
socket.on('new message',function(message){
// some logic
socket.emit('created',object);
then on the client side:
LoginActivity.mSocket.on("created", new Emitter.Listener() {
@Override
public void call(Object... args) {
Log.i( TAG, "message back:received ");
User user = new User();
JSONObject obj = null;
try {
obj = new JSONObject((String) args[0]);
//Log.i(TAG,"SdpAnswer: "+args[0].sdpAnswer+"id "+obj.sdpAnswer);
Log.i(TAG, "Instance of"+args[0].toString());
}
});
}
But for some reason it never receives the message. Anyone have some ideas why that may be? Thank you!
Upvotes: 3
Views: 2671
Reputation: 180
OK so i figured it out after some more searching. It seems that in order to maintain correctly the socket connection for different android activities I had to implement a singleton class where i have defined the socket connection.The problem was that i instantiated the socket connection in one activity and tried to use that connection on another and even if I could send messages on another activity I could not receive any unless I moved the socket to the activities where the messages where received. You can find a lot of examples on how to implement a singleton class so it's not to hard and it solved my problem. Have a nice day :)
Upvotes: 1
Reputation: 41
If you are using the socket.io library by nkzawa as per the docs you have to process the internals of the call method using a runonUIThread method.
import com.github.nkzawa.emitter.Emitter;
private Emitter.Listener onNewMessage = new Emitter.Listener() {
@Override
public void call(final Object.. args) {
getActivity().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);
}
});
}
};
This is what onNewMessage looks like. A listener is an instance of Emitter.Listener and must be implemented the call method. You’ll notice that inside of call() is wrapped by Activity#runOnUiThread(), that is because the callback is always called on another thread from Android UI thread, thus we have to make sure that adding a message to view happens on the UI thread.
Refer to this link for more info: Native Socket.IO and Android
Upvotes: 2