简体   繁体   中英

socket.io-client java not connecting to server

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

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();

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