Nodejs combined with Socket.IO to realize websocket instant communication

Nodejs combined with Socket.IO to realize websocket instant communication

Why use websocket

Websocket is a network communication protocol, generally used for real-time communication.

The websocket protocol is similar to the http protocol. The http protocol has a flaw in that it can only be initiated by the client side, and the server side returns the corresponding result based on the request URL and the parameters passed.

Websocket is雙向通信. Once the websocket connection is established, the client can send data to the server, and the server can also actively send data to the client.

Websocket is applicable to scenarios such as web chat rooms, web customer service, and instant messaging scenarios where the front-end and back-end frequently exchange data.

Socket.io

A bidirectional and low-latency websocket communication package with high performance, high reliability and scalability.
(To put it simply, it is to encapsulate and optimize websocket.)

insert image description here

Socket.IO is a library that enables real-time, bidirectional, event-based communication between browsers and servers. It includes:

  • Server
  • Client

insert image description here

Official website
https://socket.io/
Official Documentation
https://socket.io/docs/v4/

Open Source Projects

The following code and time items will be published in the open source project [nodejs-study], welcome to download and study

Effect Preview

After entering node app to run the service, you can access it through http://localhost:3000/. If you see the output listening to port 3000 and the front-end displays hello world, the project has been successfully started.

insert image description here

Front-end page: a chat UI box, including sending and receiving functions http://localhost:3000/test

insert image description here

Background websocket: listening and replying

insert image description here

app.js

First you need to install the express and socket.io libraries

Type npm install express --save or yarn add express

Type npm install socket.io--save or yarn add socket,io

Next, we will monitor the two paths / and /test

  • / Return to hello world
  • /test returns to the html connection page

socket.on ("chat message", callback function)
Indicates starting to monitor the "chat message" channel, as long as the frontend and backend are the same channel.

socket.emit ("chat message", msg.toUpperCase());
Indicates a reply to this "chat message" channel. We will temporarily capitalize the English letters and return it.

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);

app.get('/', (req, res) => {
    res.send('<h1>Hello world</h1>');
  });

app.get('/test', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

// io.on('connection', (socket) => {
// console.log('a user connected');
// });
//by zhengkai.blog.csdn.net
//Process socket.on information and socket.emit reply information //Here, capitalize the received msg io.on('connection', (socket) => {
    //Socket.io by zhengkai.blog.csdn.net
    socket.on('chat message', (msg) => {
      console.log('received: ' + msg);
      socket.emit("chat message", msg.toUpperCase());
    });
  });
//Listen on port 3000
server.listen(3000, () => {
  console.log('listening on *:3000');
});

index.html

This does some styling, and has the following body content:

  • The ul of message can be used to append li information to display the records of transactions.
  • A form to submit the information to be sent

As for the script part, first use the official socket.io js client to initialize a connection and add a listening event:

  • After entering non-empty content and submitting it, the information is sent to the websocket backend and is also output in the information list
  • After receiving the message, it will be displayed in the message list
<!DOCTYPE html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      body { margin: 0; padding-bottom: 3rem; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }

      #form { background: rgba(0, 0, 0, 0.15); padding: 0.25rem; position: fixed; bottom: 0; left: 0; right: 0; display: flex; height: 3rem; box-sizing: border-box; backdrop-filter: blur(10px); }
      #input { border: none; padding: 0 1rem; flex-grow: 1; border-radius: 2rem; margin: 0.25rem; }
      #input:focus { outline: none; }
      #form > button { background: #333; border: none; padding: 0 1rem; margin: 0.25rem; border-radius: 3px; outline: none; color: #fff; }

      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages > li { padding: 0.5rem 1rem; }
      #messages > li:nth-child(odd) { background: #efefef; }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form id="form" action="">
      <input id="input" autocomplete="off" /><button>Send</button>
    </form>
  </body>
  <script src="/socket.io/socket.io.js"></script>
  <script>
    var socket = io();
    
    var messages = document.getElementById('messages');
    var form = document.getElementById('form');
    var input = document.getElementById('input');

    //Output to screen function addMessage(str){
        const li = document.createElement("li")
        li.innerHTML=str;
        messages.appendChild(li); 
        
    }
    // console.log(form)
    form.addEventListener('submit', function(e) {
      e.preventDefault();
      if (input.value) {
        //Socket.io by zhengkai.blog.csdn.net
        let msg = 'Send message:' + input.value;
        console.log(msg)
        socket.emit('chat message', input.value);
        addMessage(msg);
        //Clear an input box//input.value = '';
      }
    });
    socket.on("chat message", (arg) => {
        let msg = 'Receive message:' + arg;
        console.log(msg); // world
        addMessage(msg);
    }); 
  </script>
  
</html>

This is the end of this article about nodejs combined with Socket.IO to implement websocket instant messaging. For more related node websocket instant messaging content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Nodejs and react to realize the function of simple instant messaging chat room
  • NodeJs implements simple WebSocket instant messaging sample code
  • Method of using MQTT protocol to realize instant messaging and offline push in Node.js
  • Detailed explanation of the instant messaging function implemented by nodejs combined with Socket.IO
  • 4 ways to implement instant messaging with JavaScript

<<:  N ways to cleverly implement adaptive dividers with CSS

>>:  Web Design Tips: Simple Rules for Page Layout

Recommend

Solution to the same IP after cloning Ubuntu 18 virtual machine

Preface I recently used a virtual machine to inst...

A brief introduction to JavaScript arrays

Table of contents Introduction to Arrays Array li...

HTML Tutorial: Collection of commonly used HTML tags (6)

These introduced HTML tags do not necessarily ful...

Generate OpenSSL certificates in Linux environment

1. Environment: CentOS7, Openssl1.1.1k. 2. Concep...

Introduction to setting up Tomcat to start automatically on Linux system

1. Enter the /etc/init.d directory: cd /etc/init....

Solution to Mysql binlog log file being too large

Table of contents 1. Related binlog configuration...

Vue component communication method case summary

Table of contents 1. Parent component passes valu...

Talk about how to identify HTML escape characters through code

Occasionally you'll see characters such as &#...

js to implement verification code interference (dynamic)

This article example shares the specific code of ...

Detailed explanation of commonly used nginx rewrite rules

This article provides some commonly used rewrite ...

Two ways to export csv in win10 mysql

There are two ways to export csv in win10. The fi...

Why should MySQL fields use NOT NULL?

I recently joined a new company and found some mi...

WeChat applet realizes taking photos and selecting pictures from albums

This article shares the specific code for WeChat ...