简体   繁体   中英

Communicating using socketio in Android - socket.emit error

I'm trying to communicate to my nodejs application using android as client. Currently I'm using https://github.com/Gottox/socket.io-java-client repository as reference. Tried the examples of repo but no help.

NodeJS-SocketIO Code:

socket.on('new user',function(data, callback){
    if (nicknames.indexOf(data)!=-1){
        callback(false);
    } else{
        callback(true);
        socket.nickname = data;
        nicknames.push(socket.nickname);
        updateNicknames();
    }
});

Android-Java Code:

try {
                JSONObject json = new JSONObject();
                json.putOpt("data", "user1");
                socket.emit("new user", json);

            } catch (JSONException ex) {
                ex.printStackTrace();
    }

However, the above code results in TypeError: undefined. Please help. Thanks in advance!

You can do away with the JSON object . You could just do:

socket.emit("new user", "user1");

Not so sure about sending a JSON over, but if you wanted to, did you try:

JSONArray array = new JSONArray();
array.put("data", "user1");
socket.emit("new user", array);

Pretty sure JSONs need to have the enclosing brackets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM