This article shares the specific code of node+socket to implement a simple chat room for your reference. The specific content is as follows Serverconst net = require('net') const server = net.createServer() //User list let clients = [] //Listen for connections 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(`User ${name} is online`) }else{ for (const client of clients) { if(client.name!==JSON.parse(data).name){ client.write(data) } } } }) client.on('close',()=>{ console.log(`User ${client.name} is offline`) }) client.on('error',()=>{ console.log(`An error occurred for user ${client.name}`) }) }) server.on('error',(err)=>{ console.log('Server error',err) }) server.on('close',()=>{ console.log('Server shutdown') }) server.listen(9527,()=>{ console.log("Server started") }) Clientconst net = require('net') const readline = require('readline') //Read input information const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); //name const name = process.argv[2] //Connect to the server const client = net.createConnection({port:9527},()=>{ console.log(name+'connect to server'); client.write(`login:${name}`) client.name = name //Start sending information 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('Disconnected from server'); }); client.on('error', () => { console.log('Server error'); }); //Recursive output function sendMsg(client){ rl.question('',(line)=>{ client.write(JSON.stringify({ name:client.name, msg:line })) sendMsg(client) }) } DemoServer Client 1 Client 2 The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM. You may also be interested in:
|
<<: MySql 8.0.16-win64 Installation Tutorial
>>: Implementation of Docker cross-host network (manual)
Table name and fields –1. Student List Student (s...
Introduction to jsvc In production, Tomcat should...
Core code /*-------------------------------- Find...
By default, PHP on CentOS 7 runs as apache or nob...
Table of contents 1. What is two-way data binding...
background The Agile model is widely used, and te...
Remote connection to MySQL fails, there may be th...
ElasticSearch cluster supports動態請求的方式and靜態配置文件to ...
Hello everyone! I am Mr. Tony who only talks abou...
Navigation and other things are often used in dai...
I recently encountered a feature while working on...
Table of contents 1. Initialize the array 2. Arra...
Environment Introduction: Ubuntu Server 16.04.2+M...
Simply use CSS to achieve all the effects of corn...
Routing configuration commands under Linux 1. Add...