0

I am having trouble sending a JSONArray through socket.io in JAVA.

With the function below i am trying to authorize the user with his username and token.

public static void authorize()
    {
        HashMap<String, String> user = Database.getUser();

        JSONArray req = new JSONArray();

        try {
            JSONObject reqObj = new JSONObject();
            reqObj.put("username", user.get("username"));
            req.put( reqObj );
            reqObj = new JSONObject();
            reqObj.put("usertoken", user.get("usertoken"));
            req.put( reqObj );
        } catch (JSONException e) {
            e.printStackTrace();
        }

        Log.d("WebsocketFunctions", "Authorize: " + req.toString());
        Socket.emit("authorize", req);
    }

This is the Log.d("WebsocketFunctions") output:

Authorize: [{"username":"admin"},{"usertoken":"45345980983450983"}]

But on my node server i only get:

debug - websocket writing 1:: {username : 'admin'}

What i need is not only the username, but also the usertoken. Somehow the usertoken is not send to the server.

This is my node authorize function:

authorize: function(socket, data)
        {
            console.log('Authorize');
            console.log(data);
        },

1 Answer 1

2

I don't know where is the problem but one thing I'm sure about is that you can do this without JSONArray. I do this and this works:

JSONObject obj = new JSONObject();
obj.putOpt("username", user.get("username"));
obj.putOpt("usertoken", user.get("usertoken"));
socket.emit("authorize", obj);

If you want to send int or double then use this:

obj.put("key", value);

You can access it in socket.io server this way:

socket.on("authorize", function(data) {
   var user = data.username;
   var token = data.usertoken;
})
Sign up to request clarification or add additional context in comments.

2 Comments

I use github.com/koush/android-websockets as websocket. But it cannot handle a JSONObject as param. Only a JSONArray
I see. I thought you were using "github.com/Gottox/socket.io-java-client"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.