Nodejs:如何使用Nodejs net.socket

时间:2016-02-17 15:57:16

标签: node.js sockets tcp

我有两个命令发送到服务器,首先前进,获得确认,然后发送下一个命令向后移动。我写了两个单独的java脚本文件来实现这一点。是否可以写入单一功能。我正在尝试下面的代码,但只有前进命令被发送到服务器。

var net = require('net');

var HOST = '127.0.0.1';
var PORT = 1850;

var client = new net.Socket();
client.connect(PORT, HOST, function() {
    console.log('CONNECTED TO: ' + HOST + ':' + PORT);
    client.write('READER_FWD');
    //client.end();
});

client.on('data', function(data) {
    console.log('DATA: ' + data);
    //client.destroy();
    // 

    if (data == 'ACK')
    {
        console.log('DATA1: ' + data);
        client.end();
        console.log('DATA2: ' + data);
        client.connect(PORT, HOST, function() {
            console.log('CONNECTED TO: ' + HOST + ':' + PORT);
            client.write('READER_BWD');
            //client.end();
            console.log('DATA3: ' + data);
        });

    }
    client.end();
});

client.on('end', function() {
    console.log('disconnected from server');
});

client.on('error', function(err) {
   console.log(err)
});

2 个答案:

答案 0 :(得分:1)

我已经更新了代码,正如你正确地指出连接在写入时越来越近,我添加了一些延迟。

var net = require('net');


var config = {
    host: '127.0.0.1',
    port: 1850
};

var move = {
    forward: 'READER_FWD',
    backward: 'READER_BWD'
};

var client = new net.Socket();

client.connect({
        host: config.host,
        port: config.port
    }, function () {
        console.log('connected to ' + config.host + ':' + config.port);
        client.write(move.forward, function () {
            console.log('move forward command sent');
        });
});

client.on('data', function (data)
 {
    var str = data.toString();

    if (str === 'ACK') 
    {

        setTimeout(function() 
        {   
            console.log('ACK received');
            client.write(move.backward, function () 
            {
                console.log('move backward sent');
                client.end();

            }); 
        }, 3000);

    }

});

client.on('error', function (err) {
    console.log('Error : ', err);
});

client.on('close', function () {
    console.log('socket closed');
});

答案 1 :(得分:0)

您无需结束插座并在“数据”中重新打开插座。监听器。你可以保持同一个插座。

这是我发送命令的client.js文件:

var net = require('net');
var config = {
    host: '127.0.0.1',
    port: 1850
};

var move = {
    forward: 'READER_FWD',
    backward: 'READER_BWD'
};

var client = new net.Socket();

client.connect({
        host: config.host,
        port: config.port
    }, function () {
        console.log('connected to ' + config.host + ':' + config.port);
        client.write(move.forward, function () {
            console.log('move forward command sent');
        });
});

client.on('data', function (data) {
    var str = data.toString();
    if (str === 'ACK') {
        console.log('ACK received');
        client.write(move.backward, function () {
            console.log('move backward sent');
            client.end();
        });
    }
});

client.on('error', function (err) {
    console.log('Error : ', err);
});

client.on('close', function () {
    console.log('socket closed');
});

connect()方法将套接字连接到服务器并向其发送forward命令。它和你的完全一样。

然后,问题来自您的数据'监听器。您的数据监听器必须执行以下操作(如您在说明中所提到的):

  1. 从服务器获取数据
  2. 如果是ACK消息:发送反向命令
  3. 然后,关闭连接(如果需要,如果没有,请保持活动状态)
  4. 注意以下几点:套接字nodejs documentation for the event 'data'表示我们收到了Buffer。因此,您需要将其转换为String以与另一个字符串进行比较,并使用此the .toString() method of the Buffer

    因此,正如Nodejs net.Socket与事件一起使用,我不认为可以发送转发命令,听取数据'事件并发送后退命令。

    首先,这不是一个好主意,因为你会把数据放在'连接后的监听器,你可能会错过一些数据! 其次,因为它是基于事件的,所以你应该创建遵循这个过程的架构:)

    以下是我的服务器代码:

    var net = require('net');
    var port = 1850;
    var move = {
        forward: 'READER_FWD',
        backward: 'READER_BWD'
    };
    
    var server = net.createServer(function (client) {
        console.log('client connected');
    
        client.on('end', function () {
            console.log('client disconnected');
        });
    
        client.on('data', function (data) {
            var str = data.toString();
            if (str === move.forward) {
                console.log('move forward command received');
                client.write('ACK', function () {
                    console.log('ACK sent');
                });
            } else if (str === move.backward) {
                console.log('move backward command received: do nothing...');
            } else {
                console.log('unknown received message: ', str);
            }
        });
    });
    
    server.listen(port, function () { //'listening' listener
        console.log('server bound on port: ' + port);
    });
    

    如果需要,这里也是输出:

    服务器:

    server bound on port: 1850
    client connected
    move forward command received
    ACK sent
    move backward command received: do nothing...
    client disconnected
    

    客户端:

    connected to 127.0.0.1:1850
    move forward command sent
    ACK received
    move backward sent
    socket closed
    

    我希望它能回答这个问题。随意询问是否有任何问题。