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('http').createServer() let io = require('socket.io')(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('socket.io')(app, { serveClient: false })
Method 2: Call the function serverClient
let app = require('http').createServer() let io = require('socket.io')() 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('socket.io')(app, { path: '/io' })
Call function path
let app = require('http').createServer() let io = require('socket.io')() io.path('/io') 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('http://localhost:3000?token=abc') socket.on('connect', () => { console.log('connect') }) socket.on('connect_error', err => { socket.disconnect() console.log('connect_error', err) })
The back-end allowRequest determines whether to continue based on the token
let app = require('http').createServer() let io = require('socket.io')(app, { allowRequest: (req, cb) => { if (req._query && req._query.token === 'abc') return cb(null, true) cb(null, false) } });
origins<br>
You can limit the source
1. Restrict the source when instantiating
let app = require('http').createServer() let io = require('socket.io')(app, { origins: 'http://localhost:3000' })
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('http://localhost:*') io.origins((origin, cb) => { if (origin === 'http://localhost:3000/') 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 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
let editSocket = io('edit.socket.test') let messageSocket = io('message.socket.test')2 , Namespace: Only run an independent service, isolate through namespace
let app = require('http').createServer() let io = require('socket.io')(app) let editServer = io.of('/edit') let messsageServer = io.of('/message') editServer.on('connection', socket => { //编辑相关 }) messsageServer.on('connection', socket => { /消息相关 })
let editSocket = io('socket.test/edit') let messageSocket = io('socket.test/message')3. Event name convention: Isolate by adding event name
let app = require('http').createServer() let io = require('socket.io')(app) io.on('connection', socket => { //编辑相关 io.emit('edit:test') io.on('edit:test', data => { }) //消息相关 io.emit('message:test') io.on('message:test', 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 instantiatedlet app = require('http').createServer() let io = require('socket.io')(app) io.sockets // io.of('/').sockets io.emit // 代理io.of('/').emit, 类似函数有'to', 'in', 'use', 'send', 'write', 'clients', 'compress'
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('Authentication error')) })
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群的概率.
socket.join('room name') //进入 socket.leave('room name') //退出
io.to('some room').emit('some event') // io.to与io.in同义,向某个聊天室的所有成员发送消息
默认聊天室<br>
每个socket在连接成功后会自动创建一个默认个聊天室,这个聊天室的名字是当前socket的id,可以通过默认聊天室实现向特定用户发送消息
socket.on('say to someone', (id, msg) => { socket.broadcast.to(id).emit('my message', msg) })
消息发送<br>
应答消息<br>
普通消息不需要回应,而应答消息提供了应答机制
io.on('connection', socket => { socket.emit('an event', { some: 'data' }) //普通消息 socket.emit('ferret', 'tobi', function (data) { //应答消息 console.log(data); // data will be 'woot' }) })
<br>
socket.on('ferret', (name, fn) => { fn('woot') })
压缩<br>
socket.compress(true)
启用压缩,调用后当前连接的所有数据在传递给客户端前都会进行压缩
volatile标志<br>
socket.io在正常情况下对发送的消息进行追踪,确保消息发送成功,而设置volatile后发送消息,socket.io不会对消息追踪,消息可能丢失
分类
// 客户端发送消息 socket.emit('hello', 'can you hear me?', 1, 2, 'abc'); // 向所有连接的客户端(除了自己)发送消息 socket.broadcast.emit('broadcast', 'hello friends!'); // 向game聊天室发送消息,自己不算 socket.to('game').emit('nice game', "let's play a game"); // 同时向game1和game2聊天室发送消息,自己不算 socket.to('game1').to('game2').emit('nice game', "let's play a game (too)"); // 向game聊天室的所有人发送消息 io.in('game').emit('big-announcement', 'the game will start soon'); // 发送消息到<socketid>客户端 socket.to(<socketid>).emit('hey', 'I just met you'); // 发送应答消息 socket.emit('question', 'do you think so?', 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!

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.

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.

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

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.

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


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

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

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6
Visual web development tools

Dreamweaver Mac version
Visual web development tools

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

WebStorm Mac version
Useful JavaScript development tools
