search
HomeWeb Front-endJS TutorialIntroduction 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<br>

socket.io will provide socket.io.min through the socket.io-client package by default. js and socket.io.js.map download<br>

Run the instance app.js

let app = require(&#39;http&#39;).createServer() 
let io = require(&#39;socket.io&#39;)(app)

app.listen(3000);

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

let io = require(&#39;socket.io&#39;)(app, { 
 serveClient: false
})

Method 2: Call the function serverClient

let app = require(&#39;http&#39;).createServer() 
let io = require(&#39;socket.io&#39;)() 
io.serveClient(false) 
io.listen(app) // 或者io.attach(app)

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

let io = require(&#39;socket.io&#39;)(app, { 
 path: &#39;/io&#39;
})

Call function path

let app = require(&#39;http&#39;).createServer() 
let io = require(&#39;socket.io&#39;)() 
io.path(&#39;/io&#39;) 
io.listen(app)

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

let socket = io(&#39;http://localhost:3000?token=abc&#39;) 
socket.on(&#39;connect&#39;, () => { 
 console.log(&#39;connect&#39;)
})
socket.on(&#39;connect_error&#39;, err => { 
 socket.disconnect()
 console.log(&#39;connect_error&#39;, err)
})

The back-end allowRequest determines whether to continue based on the token

let app = require(&#39;http&#39;).createServer() 
let io = require(&#39;socket.io&#39;)(app, { 
 allowRequest: (req, cb) => {
 if (req._query && req._query.token === &#39;abc&#39;) return cb(null, true)
 cb(null, false)
 }
});

origins<br>

You can limit the source

1. Restrict the source when instantiating

let app = require(&#39;http&#39;).createServer() 
let io = require(&#39;socket.io&#39;)(app, { 
 origins: &#39;http://localhost:3000&#39;
})

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

io.origins(&#39;http://localhost:*&#39;)

io.origins((origin, cb) => { 
 if (origin === &#39;http://localhost:3000/&#39;) return cb(null, true)
 cb(null, false)
})

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 significance

We 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>

Use socket.io to implement this application, which has the following forms

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

let editSocket = io(&#39;edit.socket.test&#39;) 
let messageSocket = io(&#39;message.socket.test&#39;)

2 , Namespace: Only run an independent service, isolate through namespace

let app = require(&#39;http&#39;).createServer() 
let io = require(&#39;socket.io&#39;)(app) 
let editServer = io.of(&#39;/edit&#39;) 
let messsageServer = io.of(&#39;/message&#39;) 
editServer.on(&#39;connection&#39;, socket => { 
 //编辑相关
})
messsageServer.on(&#39;connection&#39;, socket => { 
 /消息相关
})
let editSocket = io(&#39;socket.test/edit&#39;) 
let messageSocket = io(&#39;socket.test/message&#39;)

3. Event name convention: Isolate by adding event name

let app = require(&#39;http&#39;).createServer() 
let io = require(&#39;socket.io&#39;)(app)

io.on(&#39;connection&#39;, socket => { 
 //编辑相关
 io.emit(&#39;edit:test&#39;)
 io.on(&#39;edit:test&#39;, data => {

 })
 //消息相关
 io.emit(&#39;message:test&#39;)
 io.on(&#39;message:test&#39;, data => {

 })
}

Invasiveness of the program through event name convention It is too large and is not conducive to splitting and reorganization, so it is not recommended. The completely independent mode requires the use of two socket connections, which wastes the number of concurrent connections allowed by the browser and consumes more server resources. Using namespaces can achieve good isolation without wasting resources.

Default namespace<br>

The namespace with the path / is automatically bound to the namespace with path / when socket.io is instantiated

let app = require(&#39;http&#39;).createServer() 
let io = require(&#39;socket.io&#39;)(app)

io.sockets // io.of(&#39;/&#39;).sockets 
io.emit // 代理io.of(&#39;/&#39;).emit, 类似函数有&#39;to&#39;, &#39;in&#39;, &#39;use&#39;, &#39;send&#39;, &#39;write&#39;, &#39;clients&#39;, &#39;compress&#39;

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

io.use((socket, next) => { 
 if (socket.request.headers.cookie) return next()
 next(new Error(&#39;Authentication error&#39;))
})

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>

Comparison with allowRequest

<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>

Comparison with connection event

<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群的概率.

socket.join(&#39;room name&#39;) //进入 
socket.leave(&#39;room name&#39;) //退出
io.to(&#39;some room&#39;).emit(&#39;some event&#39;) // io.to与io.in同义,向某个聊天室的所有成员发送消息

默认聊天室<br>

每个socket在连接成功后会自动创建一个默认个聊天室,这个聊天室的名字是当前socket的id,可以通过默认聊天室实现向特定用户发送消息

socket.on(&#39;say to someone&#39;, (id, msg) => { 
 socket.broadcast.to(id).emit(&#39;my message&#39;, msg)
})

消息发送<br>

应答消息<br>

普通消息不需要回应,而应答消息提供了应答机制

io.on(&#39;connection&#39;, socket => { 
 socket.emit(&#39;an event&#39;, { some: &#39;data&#39; }) //普通消息

 socket.emit(&#39;ferret&#39;, &#39;tobi&#39;, function (data) { //应答消息
 console.log(data); // data will be &#39;woot&#39;
 })
})

<br>

socket.on(&#39;ferret&#39;, (name, fn) => { 
 fn(&#39;woot&#39;)
})

压缩<br>

socket.compress(true)启用压缩,调用后当前连接的所有数据在传递给客户端前都会进行压缩

volatile标志<br>

socket.io在正常情况下对发送的消息进行追踪,确保消息发送成功,而设置volatile后发送消息,socket.io不会对消息追踪,消息可能丢失

分类

// 客户端发送消息
socket.emit(&#39;hello&#39;, &#39;can you hear me?&#39;, 1, 2, &#39;abc&#39;);

// 向所有连接的客户端(除了自己)发送消息
socket.broadcast.emit(&#39;broadcast&#39;, &#39;hello friends!&#39;);

// 向game聊天室发送消息,自己不算
socket.to(&#39;game&#39;).emit(&#39;nice game&#39;, "let&#39;s play a game");

// 同时向game1和game2聊天室发送消息,自己不算
socket.to(&#39;game1&#39;).to(&#39;game2&#39;).emit(&#39;nice game&#39;, "let&#39;s play a game (too)");

// 向game聊天室的所有人发送消息
io.in(&#39;game&#39;).emit(&#39;big-announcement&#39;, &#39;the game will start soon&#39;);

// 发送消息到<socketid>客户端
socket.to(<socketid>).emit(&#39;hey&#39;, &#39;I just met you&#39;);
// 发送应答消息
socket.emit(&#39;question&#39;, &#39;do you think so?&#39;, function (answer) {});

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools