简体   繁体   English

在node.js上聊天

[英]Chat on node.js

Require the modules 需要模块

var net = require("net");

Store the users and the connections number var count = 0, users = {}; 存储用户和连接号var count = 0,users = {};

Creates the server 创建服务器

var server = net.createServer(function (conn){

Stores the current nickname and set the utf8 encoding 存储当前昵称并设置utf8编码

var nickname;
conn.setEncoding('utf8');

Shows a message on the shell when you stablish a connection 建立连接时在外壳上显示一条消息

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: ');

The number of connections++ 连接数++

count++;

When recives data it checks if there is a user in the storage with that name shows a message and return. 接收数据时,它会检查存储中是否存在该名称的用户,并显示一条消息并返回。 Else shows a welcome message. 其他显示欢迎消息。 Otherwise, if you input a message or any data (after have registered your nickname) shows it on the shell. 否则,如果您输入消息或任何数据(在注册您的昵称后)在外壳上显示该消息。

conn.on('data', function (data){
    data = data.replace('\r\n', '');
    if(!nickname) {
        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 {
        for(var i in users) {
            if(i != nickname) {
                users[i].write('\033[96m > ' + nickname + ':\033[39m ' + data + '\n');
            }
        }
    }
});

When you close or end the connection deletes your nickname from the storage, number of connections-- and shows a message. 关闭或结束连接后,连接将从存储中删除您的昵称,连接数-并显示一条消息。

conn.on('close', function(){
    count--;
    delete users[nickname];
    conn.write('\033[90 > ' + nickname + ' left the room\033[39m\n');
});
});

Server on port 3000 服务器在端口3000上

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

I have a bug in my chat. 我的聊天中有错误。 I stablish two telnet connections using de shell. 我使用de shell建立了两个telnet连接。 But when I close one the other one close two, and shows me a error message. 但是当我关闭另一个时,我又关闭了两个,并显示一条错误消息。 What is wrong with my code? 我的代码有什么问题?

You're trying to write to a closed connection, which will fail since writing to a closed Writable stream throws an error. 您正在尝试write关闭的连接,由于写入关闭的Writable流会引发错误,因此该连接将失败。

conn.on('close', function(){
    count--;
    delete users[nickname];
    conn.write('\033[90 > ' + nickname + ' left the room\033[39m\n');
});

What you want is to broadcast the message to all other users either using Object.keys or a for-in loop. 您想要的是使用Object.keysfor-in循环将消息广播给所有其他用户。

conn.on('close', function() {
  count --;
  delete users[nickname];
  Object.keys(users).forEach(function (user) {
    users[user].write(nickname + ' left the room');
  });
}

You also don't need a separate count variable to track connected users. 您也不需要单独的count变量来跟踪已连接的用户。

Object.keys(users).length;

But when I close one the other one close two, and shows me a error message 但是当我关闭另一个时,我又关闭了两个,并显示一条错误消息

It is because you're not listening for an error event and, by default, an EventEmitter throws an error if an error occurs and no error listener is attached. 这是因为您不是在侦听error事件,并且默认情况下,如果发生错误并且未附加错误侦听器,则EventEmitter 会引发错误。

conn.on('error', console.log);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM