Home > Web Front-end > JS Tutorial > body text

Introduction to socket.io learning tutorial in node.js (3)

零下一度
Release: 2017-05-03 10:02:19
Original
1145 people have browsed it

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);
Copy after login

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
})
Copy after login

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)
Copy after login

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;
})
Copy after login

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)
Copy after login

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)
})
Copy after login

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)
 }
});
Copy after login

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;
})
Copy after login

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)
})
Copy after login

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;)
Copy after login

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 => { 
 /消息相关
})
Copy after login
let editSocket = io(&#39;socket.test/edit&#39;) 
let messageSocket = io(&#39;socket.test/message&#39;)
Copy after login

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

 })
}
Copy after login

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;
Copy after login

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;))
})
Copy after login

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;) //退出
Copy after login
io.to(&#39;some room&#39;).emit(&#39;some event&#39;) // io.to与io.in同义,向某个聊天室的所有成员发送消息
Copy after login

默认聊天室<br/>

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

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

消息发送<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;
 })
})
Copy after login

<br/>

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

压缩<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) {});
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template