Some Dissertations on Socket.io Real-time Communication

socket-io for WebSocket real-time communication

Author's Foreword

Dear readers, I would like to express my deep apologies to everyone for not being able to update the blog post recently due to some reasons. Now that those troublesome things have been resolved, daily updates should be possible. Thank you for your support, thank you!

About WebSockets

Websocket It is a protocol based on the long connection mode that can realize the instant messaging service between the browser and the server. Once the websocket link is established between the client and the server, the two can communicate anytime and anywhere

Long Connection and Short Connection in Network Communication

short connection

Short connection : The client sends a request to establish a link to the server. Once the connection is established, the client sends a message to the server, the server receives and processes it, and returns a response that the connection is disconnected .
insert image description here

Short links can optimize resource utilization on the server side
比如HTTP协议是一款基于短链接模式的协议,意味着连接建立完毕之后,客户端向服务端发送请求之后服务器响应或超时之后就会断开,如果希望再次链接就只能再去发送请求

Long connection

Long connection : The client sends a request to establish a link to the server. Once the connection is established, the client sends a message to the server, and the server receives and processes it. After the response is returned, the link will not be disconnected. Both ends can also use this link for follow - up data interaction
insert image description here

Long connection can realize instant communication between client and server

socket.io framework

Install

rear end
npm install socket.io
front-end import

Under normal circumstances, the server built by Socket.io will statically host the front-end js file /socket.io/socket.io.js, so generally it needs to be imported and registered.

<script src="/socket.io/socket.io.js"></script>
<script>
  const socket = io();
</script>

Introduction to Socket.io

Socket.io is a network operation library that encapsulates webSocket operations. Provides some simple API methods, so that the browser can easily establish a websocket link with the server segment, and communicate through this link
Official document: Portal
Chinese document: Portal

backend project

1. Create a new js file in the directory where the module is installed and name it at will.
2. We generally use socket-io to work with the http server, so we will talk about the writing and construction of this code next. The module is as follows

npm init -y 
// 初始化项目包
npm i express
// 安装express
npm i cors
// 安装cors模块解决跨域
npm i socket.io
// 安装Socket.io

3. Write the following code

const express = require('express');
// 导入express模块
const app = express();
const http = require('http');
// 导入http模块
const server = http.createServer(app);
// 注册http服务器
const {
    
     Server } = require("socket.io");
const io = new Server(server, {
    
    
  cors:{
    
    
    origin: '*'
  }
});
// 解决跨域
io.on('connection', (socket) => {
    
    
  console.log('有客户端连进来了:'+socket.id);
  socket.on('textmsg', function(data){
    
    
    // 接收到某客户端发的消息后,给所有人群发一遍即可
    io.emit('textmsg', data)   
  })
});
// io.on() 用于监听websocket事件   connection为连接建立成功事件
// 一旦客户端向服务端发送请求建立连接,连接建立成功后将触发该事件,
// 将立即执行第二个参数:回调方法
server.listen(3000, () => {
    
    
  console.log('websocket服务已启动,正在监听 *:3000');
});
// 监听端口

then start the service

node app.js
// 这个app.js是我创建的js文件命名

As shown in the figure below
insert image description here
Front-end page construction
Create a front-end html page

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>Socket.io</title>
	</head>
	<body>
        <script src="./scripts/socket.io.js">

        </script>
        <script></script>
    </body>
</html>

If this error occurs, it is a cross-domain error
insert image description here

Guess you like

Origin blog.csdn.net/weixin_50112395/article/details/126788575