Node+socket realizes simple chat room function

Node+socket realizes simple chat room function

This article shares the specific code of node+socket to implement a simple chat room for your reference. The specific content is as follows

Server

const 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")
})

Client

const 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)
    })
}

Demo

Server

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:
  • NodeJS implements a chat room function
  • Steps to build a multi-person chat room with nodejs+express
  • Nodejs realizes multi-room simple chat room function
  • Implementing a multi-person chat room based on Nodejs using socket.io
  • Node.js websocket uses socket.io library to implement real-time chat room
  • How to use Node.js Net module to realize multi-person command line chat room
  • Using sockets to create private and public chat rooms in Node.js
  • AngularJS+Node.js to implement online chat room
  • Use Angular, Nodejs, and socket.io to build chat rooms and multi-person chat rooms
  • A simple chat room function sharing implemented by nodejs

<<:  MySql 8.0.16-win64 Installation Tutorial

>>:  Implementation of Docker cross-host network (manual)

Recommend

The use of anchor points in HTML_PowerNode Java Academy

Now let's summarize several situations of con...

Blog Design Web Design Debut

The first web page I designed is as follows: I ha...

CentOS7 installation zabbix 4.0 tutorial (illustration and text)

Disable SeLinux setenforce 0 Permanently closed: ...

Recommend a cool flashing alarm button

The effect is as follows: The code is as follows ...

A brief discussion on the use of Web Storage API

Table of contents 1. Browser local storage techno...

Let IE6, IE7, IE8 support CSS3 rounded corners and shadow styles

I want to make a page using CSS3 rounded corners ...

Vue implements dynamic routing details

Table of contents 1. Front-end control 1. In the ...

MySQL master-slave data is inconsistent, prompt: Slave_SQL_Running: No solution

This article uses an example to describe the solu...

A record of a Linux server intrusion emergency response (summary)

Recently, we received a request for help from a c...

URL Rewrite Module 2.1 URL Rewrite Module Rule Writing

Table of contents Prerequisites Setting up a test...

Page Speed ​​Optimization at a Glance

I believe that the Internet has become an increas...