Reputation: 2003
I have socket.io server in nodejs which I could connect to it from JavaScript client , but from java/android I can't connect ! here is my code :
node js :
var socket = require('socket.io')();
var users = {
desktop : {},
android : {}
}
socket.on('connection',function(client){
console.log(`new connection ! ${client.id}`);
client.on('intro',(user)=>{
user.client = client ;
user.cid = client.id ;
users[user.type] = user ;
console.log('users '+users);
})
});
socket.listen(2731)
console.log(`app running`);
here is java code :
import io.socket.client.IO;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.AppCompatButton;
import android.view.View;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URISyntaxException;
public class MainActivity extends AppCompatActivity {
io.socket.client.Socket socket ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
socket = IO.socket("http://192.168.1.103:2731");
JSONObject intro = new JSONObject();
intro.put("type","android");
intro.put("id",7);
socket.emit("intro");
} catch (URISyntaxException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
setContentView(R.layout.activity_main);
}
}
I tested with localhost:2731 also firewall was off but again didn't connect. no error and no exception appears
Upvotes: 1
Views: 3190
Reputation: 1034
your code should be like this:
socket = IO.socket("http://192.168.1.103:2731");
socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
@Override
public void call(Object... args) {
JSONObject intro = new JSONObject();
intro.put("type","android");
intro.put("id",7);
socket.emit("intro");
}
};
socket.connect();
Upvotes: 2