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)
Now let's summarize several situations of con...
The first web page I designed is as follows: I ha...
Enable remote access rights for mysql By default,...
Disable SeLinux setenforce 0 Permanently closed: ...
The effect is as follows: The code is as follows ...
Table of contents 1. Browser local storage techno...
I want to make a page using CSS3 rounded corners ...
Table of contents Events in js Event Type Common ...
Table of contents 1. Front-end control 1. In the ...
This article uses an example to describe the solu...
1. Referential Integrity Referential integrity re...
Recently, we received a request for help from a c...
This article records the installation tutorial of...
Table of contents Prerequisites Setting up a test...
I believe that the Internet has become an increas...