我可以使用UDP套接字执行类似recv的操作吗?

时间:2014-04-26 11:36:35

标签: node.js udp

我是nodejs的新手,所以如果这个问题很愚蠢,请原谅我。当我用Python编写udp套接字时,我可以这样做:

socket.recvfrom(len)  # socket is udp
do_something_else
socket.recvfrom(len)

并一次接收一个特定长度的数据。 我读过节点关于UDP的文档,看来这是UDP套接字接收数据的唯一方法。

Event: ‘message’
• msg Buffer object. The message
• rinfo Object. Remote address information
Emitted when a new datagram is available on a socket. msg is a Buffer and rinfo is an object with the
sender’s address information:

socket.on(’message’, function(msg, rinfo) {
    console.log(’Received %d bytes from %s:%d\n’,
    msg.length, rinfo.address, rinfo.port);
});

不同之处在于,如果我使用消息事件,我不知道这个消息是什么。我不确定你是否理解,例如,我正在与服务器通信,第一次服务器发送给我"enter your name"并且我在do_something_else中将我的名字发回给它,然后收到{ {1}}。通过id我可以控制流程,因为我知道接下来会发生什么,但对于我如何使用消息事件来做这件事并不明显。

谢谢。

2 个答案:

答案 0 :(得分:0)

我真的不明白你的问题,你不能做这样的事情:

var states = {
        invalid_data_received: -1,
        nothing_received: 0,
        received_name: 1,
        received_some_data: 2
    },
    state = states.nothing_received;

socket.on(’message’, function(msg, rinfo) {
    msg = msg.toString();
    if (state === states.nothing_received) {
        do_something(msg);
    } else if (state === states.received_name) {
        do_something_else(msg);
    } else if (state === states.received_some_data) {
        do_even_more(msg);
    } else if (state === states.invalid_data_received) {
        // incorrect message received
    }
});

答案 1 :(得分:0)

查看此聊天演示。它使用哈希来存储用户。它演示了您的问题的解决方案。

var net = require("net");
var count = 0, users = {};
var server = net.createServer(function (conn){
var nickname;
conn.setEncoding('utf8');
conn.write(' > welcome to \033[92mnode-chat\033[39m!'
    + '\n > ' + count + ' other people are connected at this time.'
    + '\n > please write your name and press enter: ');
count++;
conn.on('data', function (data){
    data = data.replace('\r\n', '');
    if(!nickname) {//sending msg is username
        if(users[data]) {
            conn.write('\033[93m > nickname already in use. Try again:\033[39m ');
            return;
        } else {
            nickname = data;
            users[nickname] = conn;

            for(var i in users) {
                users[i].write('\033[90m > ' + nickname + ' joined the room\033[39m\n');
            }
        }
    } else {//sending msg is normal chat message
        for(var i in users) {
            if(i != nickname) {
                users[i].write('\033[96m > ' + nickname + ':\033[39m ' + data + '\n');
            }
        }
    }
});
conn.on('close', function(){
    count--;
    delete users[nickname];
    //conn.write('\033[90 > ' + nickname + ' left the room\033[39m\n');
    Object.keys(users).forEach(function (user) {
    users[user].write(nickname + ' left the room');
  });
});
conn.on('error', function(){
    console.log('\033[96m error occur.  \033[39m');
}
);

});
server.listen(3000, function (){
    console.log('\033[96m   server listening on *:3000\033[39m');
});