Implementing simple chat room dialogue based on websocket

Implementing simple chat room dialogue based on websocket

This article shares the specific code for implementing a simple chat room conversation using websocket for your reference. The specific content is as follows

First, build a node environment and write the following code in app.js

npm install socket.io-client

Socket is a high-performance server framework. Developers can develop their own network applications, such as RPC services, chat room servers, mobile game servers, etc., by implementing one or two interfaces.

npm install http-server

Generally, server services are provided. Parameters can specify ports, addresses, etc. For example, to start a service at port 8888, the command is: http-server src -p 8888

npm install koa

Koa implements a very expressive HTTP middleware framework through node.js, striving to make web application development and API usage more pleasant. Koa's middleware is executed in the stack in the order in which it is encoded, allowing you to perform operations and pass requests downward (downstream), then filter and return responses in reverse order (upstream).

Implementation Code

// Introduce dependencies const koa = require("koa")
// Initialize koa
const app = new koa()
// Enable http 
var server = require("http").createServer(app.callback())
// Initialize the socket
const io = require("socket.io")(server, { cors: true })
// Listen io.on('connection', (socket) => {
  // Actively send messages to the client setTimeout(() => {
    // Trigger a custom event through the io object method emit and send a message to the client io.emit('chat message', 'What do you want to say?')
  }, 1000)

  socket.on('disconnect', () => {
    console.log('user disconnected')
  })

  // Receive the client's message on the server // Listen to the event through the on method. When the client sends a message, the event will be triggered and the message sent by the client can be received socket.on('chat message', (msg) => {
    console.log(msg)
    // msg is the message sent by the client // Sending a message to the client is emit
    setTimeout(() => {
      msg = msg.replace("you", "me").replace("?", "").replace("?", "!")
      // Trigger event to send the processed message to the client io.emit('chat message', msg)
    }, 500)
  })
})
server.listen(5522,()=>{
  console.log('socket service is enabled, port number is 5522')
});

Call this service

import { io } from 'socket.io-client'
cteated(){
    // 1. Create a connection that can be customized this.socket = io('ws://localhost:5522')
     // 2. Establish a connection this.socket.on('connect', () => {
        console.log('Connection established successfully')
    })
    // 3. Listen for messages and return this.socket.on('chat message', msg => {
        console.log('Message returned by the service', msg)
    })
}

This will allow you to have a simple AI conversation.

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:
  • Detailed explanation of the key points of Python Socket programming
  • Websocket+Vuex implements a real-time chat software
  • Java Socket to implement multi-person chat system
  • Node.js+express+socket realizes online real-time multi-person chat room
  • Springboot Websocket Stomp message subscription push
  • Java Socket simulation to realize chat room
  • C++ implements network chat room based on socket multithreading
  • C language socketpair usage case explanation

<<:  Mycli is a must-have tool for MySQL command line enthusiasts

>>:  In-depth explanation of the locking mechanism in MySQL InnoDB

Recommend

HTML Basics: The basic structure of HTML

The basic structure of HTML hypertext documents is...

Common ways to optimize Docker image size

The Docker images we usually build are usually la...

Linux concurrent execution is simple, just do it this way

Concurrency Functions time for i in `grep server ...

Complete steps to install FFmpeg in CentOS server

Preface The server system environment is: CentOS ...

Docker container time zone error issue

Table of contents background question Problem ana...

Commonly used English fonts for web page creation

Arial Arial is a sans-serif TrueType font distribu...

How to install ELK in Docker and implement JSON format log analysis

What is ELK? ELK is a complete set of log collect...

Analysis of Linux configuration to achieve key-free login process

1.ssh command In Linux, you can log in to another...

Management of xinetd-based services installed with RPM packages in Linux

Table of contents Preface 1. Startup management b...

Detailed explanation of the use of MySQL DML statements

Preface: In the previous article, we mainly intro...

Linux redis-Sentinel configuration details

download Download address: https://redis.io/downl...

Brief analysis of the MySQL character set causing database recovery errors

Importing data with incorrect MySQL character set...

Various methods to restart Mysql under CentOS (recommended)

1. MySQL installed via rpm package service mysqld...

Ubuntu installation graphics driver and cuda tutorial

Table of contents 1. Uninstall the original drive...