利用node搭建聊天服务器

首先在编辑器里输入以下代码,我用的软件是sublime3,很好用的一款编辑器,推荐。

var net = require('net')
var chatServer = net.createServer(),
clientList = []
chatServer.on('connection', function(client) {
    client.name = client.remoteAddress + ':' + client.remotePort
    client.write('Hi ' + client.name + '!\n');
    console.log(client.name + ' joined')
    clientList.push(client)
    client.on('data', function(data) {
        broadcast(data, client)
    })
    client.on('end', function() {
        console.log(client.name + ' quit')
        clientList.splice(clientList.indexOf(client), 1)
    })
    client.on('error', function(e) {
        console.log(e)
    })
})
function broadcast(message, client) {
    var cleanup = []
    for(var i=0;i<clientList.length;i+=1) {
        if(client !== clientList[i]) {
            if(clientList[i].writable) {
                clientList[i].write(client.name + " says " + message)
                } else {
                    cleanup.push(clientList[i])
                    clientList[i].destroy()
            }
        }
    }
// 在写入循环中删除死节点,消除垃圾索引
    for(i=0;i<cleanup.length;i+=1) {
    clientList.splice(clientList.indexOf(cleanup[i]), 1)
    }
}
chatServer.listen(9000)

接下来,首先win+r,输入cmd打开终端。

然后将执行目录切换到你的代码所在的目录下,我是将代码命名为chat.js ,然后放在h盘的js文件夹下面。接着只要输入以下的代码,就运行了。

然后再打开一个终端 ,输入以下的代码就可以聊天了。

按下回车之后就行看到,已经连接上服务器了,并且会显示你的ip和端口,而在服务器端也会显示哪个客户端连接上了。

 此时再打开一个客户端连接上服务器,也会相应的显示,接下来就可以进行聊天了。

一个客户端输入相应的字符,另一个客户端就会进行显示。

当你关闭一个客户端时,在服务器端也会相应的显示。

猜你喜欢

转载自blog.csdn.net/qq_42694575/article/details/81133725