SocketIO Android没有发出连接事件

时间:2015-12-27 17:51:05

标签: android node.js sockets socket.io

我正在使用Android native socketio library和NodeJS。

    // on my Android activity
    private Socket mSocket;
    {
        try {
            mSocket = IO.socket("http://IP_OF_MY_SERVER");
        } catch (URISyntaxException e) {}
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSocket.connect();
    }

// on my nodejs app
var restify = require('restify');
var server = restify.createServer({
  name: 'myapp',
  version: '1.0.0'
});
var io = require('socket.io')(server.server);

server.use(restify.acceptParser(server.acceptable));
server.use(restify.queryParser());
server.use(restify.bodyParser());

io.on('connection', function(socket){
  console.log('a user connected');
  socket.on('new-item', function(data) {
    console.log(data);
  });
});

我正在关注官方指南,但仍然mSocket.connect()没有发出connection事件,当我启动活动时,我的控制台上没有a user connected

你能告诉我我错过了什么,我该如何调试?

修改

我的Ubuntu服务器上的NodeJS应用:http://paste.ubuntu.com/14233470/

Android活动:http://paste.ubuntu.com/14233482/

编辑2

我改变了我的代码,如建议的here

var io = require('socket.io').listen(server);

这次我在启动活动时收到此错误

myapp在http://104.131.99.145:3000收听

http.js:691
    throw new Error('Can\'t set headers after they are sent.');
          ^
Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (http.js:691:11)
    at ServerResponse.format (/var/www/biditapi.erayalakese.com/node_modules/restify/lib/response.js:145:10)
    at ServerResponse.send (/var/www/biditapi.erayalakese.com/node_modules/restify/lib/response.js:338:14)
    at emitRouteError (/var/www/biditapi.erayalakese.com/node_modules/restify/lib/server.js:201:13)
    at onRoute (/var/www/biditapi.erayalakese.com/node_modules/restify/lib/server.js:754:21)
    at Router.find (/var/www/biditapi.erayalakese.com/node_modules/restify/lib/router.js:608:5)
    at Server._route (/var/www/biditapi.erayalakese.com/node_modules/restify/lib/server.js:747:21)
    at routeAndRun (/var/www/biditapi.erayalakese.com/node_modules/restify/lib/server.js:705:14)
    at Server._handle (/var/www/biditapi.erayalakese.com/node_modules/restify/lib/server.js:725:9)
    at Server.onRequest (/var/www/biditapi.erayalakese.com/node_modules/restify/lib/server.js:326:14)
    at Server.EventEmitter.emit (events.js:98:17)
    at HTTPParser.parser.onIncoming (http.js:2108:12)
    at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:121:23)
    at Socket.socket.ondata (http.js:1966:22)
    at TCP.onread (net.js:525:27)

1 个答案:

答案 0 :(得分:2)

一些关键注意事项:

  1. 创建Socket对象:

    private Socket mSocket;
    {
        try {
            mSocket = IO.socket(CHAT_SERVER_URL); // Your server's URL
        }
        catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }
    
  2. onCreate():connect&设置套接字错误监听器

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
        mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
        mSocket.connect();
    }
    
    
    private Emitter.Listener onConnectError = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(), "Unable to connect to NodeJS server", Toast.LENGTH_LONG).show();
                }
            });
        }
    };
    
  3. 断开 onDestroy()方法中的套接字

    @Override
    protected void onDestroy() {
        super.onDestroy();
    
        mSocket.disconnect();
        mSocket.off(Socket.EVENT_CONNECT_ERROR, onConnectError);
        mSocket.off(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
    }
    
  4. 没有得到错误吐司是设置正确的第一个里程碑。

    1. 创建 WLAN
    2.   

      (使用管理员权限打开命令行,运行以下命令:)

           

      netsh wlan set hostednetwork mode = allow ssid = NodeSocket key = 1234okok

           

      netsh wlan start hostednetwork

      WLAN

      确保您的 Android 设备已连接到此网络,&您的Node.js服务器已启动&运行