本文实例为大家分享了node+socket实现简易聊天室的具体代码,供大家参考,具体内容如下
服务端
const net = require('net') const server = net.createServer() //用户列表 let clients = [] //监听连接 server.on('connection',client=>{ client.on('data',(chunk)=>{ let data = chunk.toString() if(data.match(/login:(.*)/)){ let name = data.match(/login:(.*)/)[1] client.name = name clients.push(client) console.log(`用户${name}上线`) }else{ for (const client of clients) { if(client.name!==JSON.parse(data).name){ client.write(data) } } } }) client.on('close',()=>{ console.log(`用户${client.name}下线`) }) client.on('error',()=>{ console.log(`用户${client.name}发生错误`) }) }) server.on('error',(err)=>{ console.log('服务器错误',err) }) server.on('close',()=>{ console.log('服务器关闭') }) server.listen(9527,()=>{ console.log("服务器开启") })
客户端
const net = require('net') const readline = require('readline') //读取输入的信息 const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); //名字 const name = process.argv[2] //连接服务器 const client = net.createConnection({port:9527},()=>{ console.log(name+'连接到服务器'); client.write(`login:${name}`) client.name = name //开始发送信息 sendMsg(client) }) client.on('data', (chunk) => { let data = JSON.parse(chunk.toString()) if(data){ console.log(`[${data.name}] : ${data.msg}`) } }); client.on('end', () => { console.log('已从服务器断开'); }); client.on('error', () => { console.log('服务器错误'); }); //一直递归输出 function sendMsg(client){ rl.question('',(line)=>{ client.write(JSON.stringify({ name:client.name, msg:line })) sendMsg(client) }) }
演示
服务端
客户端1
客户端2
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持NICE源码。