Introduction to socket.io learning tutorial in node.js (3)
This article introduces you to the relevant information of socket.io in more depth. The basic tutorials and applications of socket.io have been introduced before. This article introduces the use of socket.io in more depth. Friends who need it You can use it as a reference, let’s take a look below.
Preface
socket.io provides real-time two-way communication based on events. This article introduces socket.io in depth. Let’s take a look. Detailed content.
Static files
socket.io will provide socket.io.min through the socket.io-client package by default. js and socket.io.js.map download
Run the instance app.js
1 2 3 4 |
|
Browser access http://localhost:3000/socket.io/socket.io. js can load compressed source code, visit http://localhost:3000/socket.io/socket.io.js.map to load sourcemap
We can change this behavior
Disable socket.io.js download<br/>
#Method 1: Pass in the control parameter serveClient value false during instantiation
1 2 3 |
|
Method 2: Call the function serverClient
1 2 3 4 |
|
If the service has been boundhttp.Server
before calling the function, this method will not work
After disabling it, accessing again will prompt{" code":0,"message":"Transport unknown"}
Modify the static file path<br/>
socket. The io.js path can be changed, its default path is /socket.io.
Pass parameters during instantiation
1 2 3 |
|
Call function path
1 2 3 4 |
|
If the service has been bound before calling the functionhttp.Server
, this method will Not working
Security Strategy<br/>
socket.io provides two security strategies
allowRequest<br/>
The function allowRequest has two parameters. The first parameter is the received handshake packet (http.request
) object, which is used as the basis for judgment, success), err is an error object, success is boolean, false means preventing the establishment of a connection
The front-end request brings the token
1 2 3 4 5 6 7 8 |
|
The back-end allowRequest determines whether to continue based on the token
1 2 3 4 5 6 7 |
|
origins<br/>
You can limit the source
1. Restrict the source when instantiating
1 2 3 4 |
|
2.The origins function sets the source<br/>
origins function has two forms<br/>
##origins(string): Set the running source
<br/>
origins(string, fn (err, success)): Determine whether the source is allowed through the function
1 2 3 4 5 6 |
|
Namespace<br/>
The namespace is used For server/client connection isolation, in some places, the namespace is also called a channel. The following examples illustrate its significanceWe need to implement a collaborative application, which has two functions:- Collaborative editing: multiple users can edit a document at the same time
- Message: Users can send messages between users
<br/>
1. Completely independent: There is an independent service for collaborative editing
edit.socket.test, and an independent service for the message system
message.socket.test
1 2 |
|
1 2 3 4 5 6 7 8 9 10 |
|
1 2 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
Default namespace<br/>
The namespace with the path / is automatically bound to the namespace with path / when socket.io is instantiated1 2 3 4 5 |
|
Middleware<br/>## The namespace of socket.io registers the middleware through use. After the middleware successfully establishes a connection between the client and the server, Called once before the connet event is dispatched.
Use middleware data verification
1 2 3 4 |
|
Use middleware to extract or convert data
io.use((socket, next) => {getInfo(socket.request .query.id, (err, data) => { if (err) return next(err) socket.custom = data next() }) })<br/>
<br/>allowRequest can perform some verification and extraction, why do we need middleware?
- allowRequest passes in the http.request instance, and The middleware enters and exits the data socket instance. The socket instance contains the request instance and has more information
- Middleware directly supports multiple asynchronous process nesting, while allowRequest needs to be implemented by yourself
<br/>
<br/>The connection event is also passed into the socket, and can also be used for numerical verification and extraction. Why is there a need for an intermediate event? Middleware?
- Middleware directly supports nesting of multiple asynchronous processes, while allowRequest needs to be implemented by yourself
中间件成功后到connection事件发送成功前,socket.io还做了一些工作,比如把socket实例添加到connected对象中,加入聊天室等。如果因为权限中断连接,在中间件中处理更省资源.<br/>
聊天室<br/>
聊天室是对当前连接的socket集合根据特定规则进行归组,方便群发消息。可以类比QQ群的概率.
1 2 |
|
1 |
|
默认聊天室<br/>
每个socket在连接成功后会自动创建一个默认个聊天室,这个聊天室的名字是当前socket的id,可以通过默认聊天室实现向特定用户发送消息
1 2 3 |
|
消息发送<br/>
应答消息<br/>
普通消息不需要回应,而应答消息提供了应答机制
1 2 3 4 5 6 7 |
|
<br/>
1 2 3 |
|
压缩<br/>
socket.compress(true)
启用压缩,调用后当前连接的所有数据在传递给客户端前都会进行压缩
volatile标志<br/>
socket.io在正常情况下对发送的消息进行追踪,确保消息发送成功,而设置volatile后发送消息,socket.io不会对消息追踪,消息可能丢失
分类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
The above is the detailed content of Introduction to socket.io learning tutorial in node.js (3). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The Node service built based on non-blocking and event-driven has the advantage of low memory consumption and is very suitable for handling massive network requests. Under the premise of massive requests, issues related to "memory control" need to be considered. 1. V8’s garbage collection mechanism and memory limitations Js is controlled by the garbage collection machine

This article will give you an in-depth understanding of the memory and garbage collector (GC) of the NodeJS V8 engine. I hope it will be helpful to you!

Choosing a Docker image for Node may seem like a trivial matter, but the size and potential vulnerabilities of the image can have a significant impact on your CI/CD process and security. So how do we choose the best Node.js Docker image?

The file module is an encapsulation of underlying file operations, such as file reading/writing/opening/closing/delete adding, etc. The biggest feature of the file module is that all methods provide two versions of **synchronous** and **asynchronous**, with Methods with the sync suffix are all synchronization methods, and those without are all heterogeneous methods.

Node 19 has been officially released. This article will give you a detailed explanation of the 6 major features of Node.js 19. I hope it will be helpful to you!

How does Node.js do GC (garbage collection)? The following article will take you through it.

The event loop is a fundamental part of Node.js and enables asynchronous programming by ensuring that the main thread is not blocked. Understanding the event loop is crucial to building efficient applications. The following article will give you an in-depth understanding of the event loop in Node. I hope it will be helpful to you!

The reason why node cannot use the npm command is because the environment variables are not configured correctly. The solution is: 1. Open "System Properties"; 2. Find "Environment Variables" -> "System Variables", and then edit the environment variables; 3. Find the location of nodejs folder; 4. Click "OK".
