【问题标题】:Socket.get callback not triggered in socket.on function在 socket.on 函数中未触发 Socket.get 回调
【发布时间】:2015-04-02 12:28:56
【问题描述】:

我已经在这个问题上停留了一段时间,答案可能非常基本,但我无法理解问题所在。 AFAIU 执行了函数但没有触发回调,不知道为什么。

我的脚本旨在让 tcp 服务器拥有连接 tcp 套接字的设备(树莓派)和客户端以连接到sailsjs 应用程序上的 websocket。

我设法让这两个东西都在下面的代码上运行,问题是它们只能分开工作,同时但分开,当我尝试从套接字外部获取时,一切正常,但是当我在内部执行时,io.socket 对象只是将get请求堆积在requestQueue中。

{ useCORSRouteToGetCookie: true,
  url: 'http://localhost:1337',
  multiplex: undefined,
  transports: [ 'polling', 'websocket' ],
  eventQueue: { 'sails:parseError': [ [Function] ] },
  query:'__sails_io_sdk_version=0.11.0&__sails_io_sdk_platform=node&__sails_io_sdk_language=javascript',
   _raw:
    { socket:
      { options: [Object],
        connected: true,
        open: true,
        connecting: false,
        reconnecting: false,
        namespaces: [Object],
        buffer: [],
        doBuffer: false,
        sessionid: '0xAlU_CarIOPQAGUGKQW',
        closeTimeout: 60000,
        heartbeatTimeout: 60000,
        origTransports: [Object],
        transports: [Object],
        heartbeatTimeoutTimer: [Object],
        transport: [Object],
        connectTimeoutTimer: [Object],
        '$events': {} },
     name: '',
     flags: {},
     json: { namespace: [Circular], name: 'json' },
     ackPackets: 0,
     acks: {},
     '$events':
      { 'sails:parseError': [Function],
        connect: [Object],
        disconnect: [Function],
        reconnecting: [Function],
        reconnect: [Function],
        error: [Function: failedToConnect],
        undefined: undefined } },
  requestQueue:
   [ { method: 'get', headers: {}, data: {}, url: '/', cb: [Function] },
     { method: 'get', headers: {}, data: {}, url: '/', cb: [Function] } ] }

代码如下:

//library to connect to sailsjs websockets
var socketIOClient = require('socket.io-client');
var sailsIOClient = require('sails.io.js');

//library to do the tcp server
var net = require('net');


// Instantiate the socket client (`io`)
// (for now, you must explicitly pass in the socket.io client when using this library from Node.js)
var io = sailsIOClient(socketIOClient);

// Set some options:
// (you have to specify the host and port of the Sails backend when using this library from Node.js)
io.sails.url = 'http://localhost:1337';



var server = net.createServer(function(tcpSocket) { //'connection' listener


    //socket was sucessfully connected
    console.log('client connected');

    //notify on deconnection
    tcpSocket.on('end', function() {
        console.log('client disconnected');
    });

 // Handle incoming messages from clients.
    tcpSocket.on('data', function (data) {


        console.log(data.toString('utf8', 0, data.length));

        //if data is PING respond PONG
        if(data.toString('utf8', 0, 4)=='PING'){
            console.log('I was pinged');
            tcpSocket.write('PONG\r\n'); 
        }

        console.log(io.socket);//debugging purpose
        //trigger a socket call on the sails app
        io.socket.get('/', function (body, JWR) {
            //display the result
            console.log('Sails responded with: ', body);
            console.log('with headers: ', JWR.headers);
            console.log('and with status code: ', JWR.statusCode);

        });
    });

});


server.listen(8124, function() { //'listening' listener
    console.log('server bound');
});

【问题讨论】:

  • 提示:“数据”事件可能会针对任何大小的数据包发出。所以data.length 可能是 1 也可能是 1000(它可能包含 PI 或可能包含 PING\r\n 甚至 PING\r\nHELLO\r\nPIN)。不要假设它会在行尾边界(例如\n\r\n)或类似的地方发出数据包——节点对您的应用程序级协议一无所知。

标签: node.js sockets tcp sails.js sails.io.js


【解决方案1】:

我找到了一个解决方案,我刚刚摆脱了sails.io.js 并使用了普通的socket.io,它现在可以按预期工作,尽管为什么它在sails.io.js 中没有,但可以随意解释

//library to connect to sailsjs websockets
    var socketIOClient = require('socket.io-client');
    //var sailsIOClient = require('sails.io.js');

    //library to do the tcp server
    var net = require('net');


            var socket=socketIOClient.connect('http://localhost:1337', {
'force new connection': true
});

    var server = net.createServer(function(tcpSocket) { //'connection' listener

        //socket was sucessfully connected
        console.log('client connected');

        //notify on deconnection
        tcpSocket.on('end', function() {
            console.log('client disconnected');
        });

     // Handle incoming messages from clients.
        tcpSocket.on('data', function (data) {

            console.log(data.toString('utf8', 0, data.length));

            console.log(data.toString('utf8', 0, data.length));

            //if data is PING respond PONG
            if(data.toString('utf8', 0, 4)=='PING'){
                console.log('I was pinged');
                tcpSocket.write('PONG\r\n'); 
            }

            if(data.toString('utf8', 0, 4)=='test'){

                socket.emit('test',{message : 'test'});

             //io.socket.disconnect();
            }


        });

    });

【讨论】:

    【解决方案2】:

    您的套接字似乎没有自动连接。尝试手动连接:

    // Instantiate the socket client (`io`)
    // (for now, you must explicitly pass in the socket.io client when using this library from Node.js)
    var io = sailsIOClient(socketIOClient);
    
    // Set some options:
    // (you have to specify the host and port of the Sails backend when using this library from Node.js)
    io.sails.url = 'http://localhost:1337';
    
    var socket = io.sails.connect();
    
    socket.on('connect', function() {
    
       ... connect TCP server and continue ...
    
    });
    

    【讨论】:

    • 我确实尝试过,但不幸的是它没有任何好处,我只是放弃了仅依赖 socket.io-client 的sails.io.js,按预期工作。
    猜你喜欢
    • 1970-01-01
    • 2021-06-22
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    • 2018-03-17
    • 2013-10-17
    • 1970-01-01
    • 2012-05-08
    相关资源
    最近更新 更多