首页 > 代码库 > 基于Node.js搭建TCP聊天服务器

基于Node.js搭建TCP聊天服务器

  作者:zhanhailiang 日期:2014-11-23

原理:

  1. 服务器端维持所有的客户端连接列表;
  2. 当服务器收到某个客户端的消息时,将其广播给其它的客户端连接;
  3. 当某个客户端连接退出时,将其从客户端连接列表中剔除;

实现:

var net = require(‘net‘);
var server = net.createServer();
var sockets = [];
 
// accept connection 
server.on(‘connection‘, function(socket) {
    console.log(‘got a new connection‘);
 
    // 记录当前连接用户
    sockets.push(socket);
 
    // 当收到客户端消息时将其广播给其它所有连接用户
    socket.on(‘data‘, function(data) {
        console.log(‘got data:‘, data);
        var index = sockets.indexOf(socket);
        sockets.forEach(function(otherSocket) {
            if (otherSocket !== socket) {
                otherSocket.write(new Buffer(index + ‘ say:‘));
                otherSocket.write(data);
            }
        });
    });
 
    // 删除掉线或主动退出的用户连接
    socket.on(‘close‘, function() {
        console.log(‘connection closed‘);
        var index = sockets.indexOf(socket);
        sockets.splice(index, 1);
    });
});
 
server.on(‘error‘, function(err) {
    console.log(‘Server error:‘, err.message);
});
 
server.on(‘close‘, function() {
    console.log(‘Server closed‘);
});
 
server.listen(4001);

完整代码请见: https://github.com/billfeller/professional-nodejs/blob/master/chapter10/chat_server.js

启动服务器:

[root@~/wade/nodejs/professional-nodejs/chapter10]# node chat_server.js 
got a new connection
got a new connection
got a new connection
got data: <Buffer 77 68 61 74 20 69 73 20 79 6f 75 72 20 6e 61 6d 65 0d 0a>
got data: <Buffer 69 20 61 6d 20 62 69 6c 6c 0d 0a>
got data: <Buffer 69 20 61 6d 20 66 65 6c 6c 65 72 0d 0a>
got data: <Buffer 69 20 61 6d 20 7a 75 63 6b 2c 20 6e 69 63 65 20 74 6f 20 6d 65 65 74 20 79 6f 75 0d 0a>
got data: <Buffer 6d 65 0d 0a>
got data: <Buffer 6d 65 0d 0a>
got data: <Buffer 74 6f 6f 0d 0a>

按顺序启动三个客户端连接,开始聊天:

[root@~]# telnet 127.0.0.1 4001
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is ‘^]‘.
what is your name
1 say:i am bill
2 say:i am feller
i am zuck, nice to meet you
1 say:me
2 say:me
2 say:too
[root@~]# telnet 127.0.0.1 4001
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is ‘^]‘.
0 say:what is your name
i am bill
2 say:i am feller
0 say:i am zuck, nice to meet you
me
2 say:me
2 say:too
[root@~]# telnet 127.0.0.1 4001
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is ‘^]‘.
0 say:what is your name
1 say:i am bill
i am feller
0 say:i am zuck, nice to meet you
1 say:me
me
too

参考: 《Professional Node.js》 Chapter10 Building TCP Server

基于Node.js搭建TCP聊天服务器