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

Mysql Sql statement exercises (50 questions)

Table name and fields –1. Student List Student (s...

How to start tomcat using jsvc (run as a normal user)

Introduction to jsvc In production, Tomcat should...

mysql solves the problem of finding records where two or more fields are NULL

Core code /*-------------------------------- Find...

How to install suPHP for PHP5 on CentOS 7 (Peng Ge)

By default, PHP on CentOS 7 runs as apache or nob...

Detailed explanation of Vue form binding and components

Table of contents 1. What is two-way data binding...

Solution to Navicat Premier remote connection to MySQL error 10038

Remote connection to MySQL fails, there may be th...

Detailed tutorial for installing ElasticSearch:7.8.0 cluster with docker

ElasticSearch cluster supports動態請求的方式and靜態配置文件to ...

Detailed explanation of the top ten commonly used string functions in MySQL

Hello everyone! I am Mr. Tony who only talks abou...

Vue implements top left and right sliding navigation

Navigation and other things are often used in dai...

The perfect solution for highlighting keywords in HTML

I recently encountered a feature while working on...

24 Practical JavaScript Development Tips

Table of contents 1. Initialize the array 2. Arra...