I have used https://github.com/Gottox/socket.io-java-client for socket programming in android. Now i am receiving JSON response and now i want to send JSON data to this node.js server from my android application please help me out. here is my code
buttonConnect.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// socket = null;
try {
SocketIO socket = new SocketIO(
"http://104.131.225.38:8001/");
socket.connect(new IOCallback() {
@Override
public void onMessage(JSONObject arg0,
IOAcknowledge arg1) {
try {
Log.i("Server saidwsssss:",
"sssss" + arg0.toString(2));
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onMessage(String arg0, IOAcknowledge arg1) {
Log.i("Server said:", "" + arg0);
}
@Override
public void onError(SocketIOException arg0) {
Log.i("OnError", "" + arg0);
}
@Override
public void onDisconnect() {
Log.i("Connection Terminated",
"Connection Terminated");
}
@Override
public void onConnect() {
Log.i("Connection Established",
"Connection Established");
}
@Override
public void on(String arg0, IOAcknowledge arg1,
Object... arg2) {
Log.i("Server Trigger Event:", "" + arg0 + ""
+ arg1);
if (arg0.equals("nbUsers")) {
Log.i("DONE", "DONE" + arg0.toString());
}
Object[] arguments = arg2;
Log.i("Args", "" + arguments[0].toString());
}
});
socket.send("hello server");
socket.emit("event", "argument1", "argument2", 13.37);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
You can use a Gson object that permit to transform your object into a JSON String, and apply a conversion to a JSONObject like this :
Entity en = new Entity();
Gson gson = new Gson();
try {
JSONObject obj = new JSONObject(gson.toJson(en));
socket.emit("entity", obj);
} catch (JSONException e) {
e.printStackTrace();
}
This is how I do. To use Gson, you should add a Gradle dependency :
compile 'com.google.code.gson:gson:2.+'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With