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

Example code of how to implement pivot table in MySQL/MariaDB

The previous article introduced several methods f...

Six ways to increase your website speed

1. Replace your .js library file address with the...

How to debug loader plugin in webpack project

Recently, when I was learning how to use webpack,...

SQL Server Comment Shortcut Key Operation

Batch comments in SQL Server Batch Annotation Ctr...

Causes and solutions for MySQL master-slave synchronization delay

For historical reasons, MySQL replication is base...

WeChat Mini Program video barrage position random

This article shares the specific code for randomi...

Introduction to Kubernetes (k8s)

I had always wanted to learn Kubernetes because i...

Solution to 700% CPU usage of Linux process that cannot be killed

Table of contents 1. Problem Discovery 2. View de...

Nginx configuration 80 port access 8080 and project name address method analysis

Tomcat accesses the project, usually ip + port + ...

Overview of time configuration under Linux system

1. Time types are divided into: 1. Network time (...

Solutions to the problem of table nesting and border merging

【question】 When the outer table and the inner tab...

Detailed explanation of global parameter persistence in MySQL 8 new features

Table of contents Preface Global parameter persis...