基于nodejs的tcp聊天室

server

var net = require('net');

var i = 0;

var clientList = [];

var server = net.createServer(function(socket){
    socket.name = '用户'+(++i);
    socket.write('[聊天室]欢迎'+socket.name+'\n');
    clientList.push(socket);

    function showCients(){
        console.log('[当前在线用户]:');
        for(var i = 0;i<clientList.length;i++){
            console.log(clientList[i].name);
        }
    }
    showCients();
    socket.on('data',function(data){
        for(var i = 0;i<clientList.length;i++){
            if(socket !== clientList[i]){
                clientList[i].write('['+socket.name+']'+data);
            }
        }
    });
    socket.on("close",function(){
        clientList.splice(clientList.indexOf(socket),1);
        showCients();
    });

});

server.listen(8080)

如果当前发送data的socket不等于自己,那么循环的去发送给其他的socket

Client

var net = require('net');

process.stdin.resume();

process.stdin.setEncoding('utf8');

var client = net.connect({port:8080},function(){
    console.log("本机登陆到聊天室");
    process.stdin.on('data',function(data){
        client.write(data);
    });
    client.on("data",function(data){
        console.log(data.toString());
    });

    client.on("end",function(){
        console.log("退出聊天室");
        process.exit();
    });
    client.on('"error',function(){
        console.log("出现异常");
        process.exit()
    });
});

接受终端输入数据.

你可能感兴趣的:(nodejs)