具有NodeJS的UDP聊天服务器中的用户名

时间:2015-09-07 21:40:18

标签: node.js udp server client chat

我正在使用仅使用服务器和客户端的NodeJS设置一个简单的聊天服务器。它可以工作,我可以在同一台机器上打开多个客户端窗口,但现在我需要更多。

我想:

  • 为每个客户提供设置用户名的选项
  • 让客户从服务器请求当前时间
  • 像" / me这样的动作命令可以打击术士"服务器将其他人显示为"用户打击术士"

这听起来像是一个快速的日常工作,但我刚刚开始研究UDP,除了发送和获取消息的通用服务器/客户端之外,我无法在线找到任何示例。我该如何处理这些任务? 代码:

Server.js:

var dgram = require('dgram'); //import datagram to get everything needed for UDP

var PORT = 22222;
var CLIENT_PORT = 2223;

// An IP address that's reserved on each network
// Gets sent to the server
var ADDRESS = "-"; //dont want to show my IP :)

var sock = dgram.createSocket({reuseAddr: true, type: 'udp4'}); //can now open multiple clients

var current_time = Date.now(); //?

function sendMessage(data) {
    sock.send(data, 0, data.length, PORT, ADDRESS, function(err){
       if(err){
            throw err;
       }
    });
}

sock.on("message", function(data, rinfo) {
    //listen for messages and print them
    console.log(data);

    //Check if the client's port was equal to the port to find client data on
  //If so, get packet
  if (rinfo.port === CLIENT_PORT) {
    console.log('\nreceived');

    //call function to broadcast the data out to everyone on the local network
    sendMessage(data);
 }


//Get the string data from the data buffer.
var stringData = data.toString(); //also could be toJSON()
console.log(stringData);

//Convert that string back into a buffer by making a new Buffer and passing it in.
//The buffer class can take a string, an array or just a number of bytes to allocate to memory
var backToBuffer = new Buffer(stringData); //can take a string, array or just a size to allocate
console.log(backToBuffer);

});

//This opens the connection and starts listening
//(Client Port, Address to listen to which is ALL, What to do)
sock.bind(CLIENT_PORT, '', function(){

    sock.setBroadcast(true);
    console.log('listening on port ' + PORT + "\n"); 

});

Client.js:

var dgram = require('dgram');

var SERVER_PORT = 22222;
var PORT = 22223;

var ADDRESS = "-";

//read input from the command line
var stdin = process.stdin;
var stdout = process.stdout;

var sock = dgram.createSocket({reuseAddr: true, type: 'udp4'});

var server_sock = dgram.createSocket({reuseAddr: true, type: 'udp4'});

function sendMessage(data) {
//onsole.log("sending data");
    sock.send(data, 0, data.length, PORT, ADDRESS, function(err) {
        if(err) {
             throw err;
        }
        //nsole.log("sent");
    });
}

server_sock.on("message", function(data, rinfo) {
    console.log("received " + data.toString());
});

server_sock.bind(SERVER_PORT, '', function() {
    console.log('listening to server port');
});

sock.bind(PORT, '', function() {
    sock.setBroadcast(true);
    console.log("please enter a message\n");

    stdin.resume();

    stdin.on("data", function(data) {
        sendMessage(data);
    });
});

1 个答案:

答案 0 :(得分:0)

Node.js有大量的库来进行实时通信聊天,我不明白选择使用UDP并自己管理所有内容,而且看起来你对此并不是很专业。我的建议是使用一个websocket库,就像它可以是socket.io一样,他们甚至在他们的网站上有一个简单聊天的例子http://socket.io/get-started/chat/

使用socket.io(或类似的)它会帮助你很多,因为它有会话,所以你可以保存用户名并在每次发布消息时返回它。 下面我写了一个服务器端的小例子(取自上面的get-started的index.js)。

io.on('connection', function(socket){
    var username = 'RANDOM';
  socket.on('chat message', function(msg){
    //here you should catch messages starting with "/" and parse them to write a different message
    io.emit('chat message', username + ': ' msg);
  });
  socket.on('update username', function(msg) {
    username = msg;
    io.emit('username changed', username);
  });
});

我希望它有所帮助。