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
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:<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')
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')
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 => { }) }
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?
<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?
中间件成功后到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!