socket.io供应了基于事宜的及时双向通信
服务端与客户端衔接
socket.io同时供应了服务端和客户端的API
服务端socket.io必需绑定一个http.Server实例
绑定http.Server
隐式绑定
经由过程实例化时传入端口或实例化后挪用listen
或attach
函数举行隐式绑定。socket.io内部实例化并监听http.Server
实例化时传入端口
let io = require('socket.io')(3000)
直接经由过程
listen
或attach
函数绑定。listen
与attach
同义
let io = require('socket.io')
io.listen(3000) // io.attach(3000)
显现绑定
能够手动指定http.Server
实例化时绑定
let server = require('http').Server();
let io = require('socket.io')(server)
server.listen(3000)
经由过程
listen
或attach
绑定
let server = require('http').Server();
let io = require('socket.io')()
io.listen(server) // io.attach(server)
server.listen(3000)
能够绑定express或koa等http框架
express
let app = require('express')
let server = require('http').Server(app)
let io = require('socket.io')(server)
app.listen(3000)
koa
let app = require('koa')()
let server = require('http').Server(app.callback())
let io = require('socket.io')(server)
app.listen(3000)
监听衔接状况
当服务器端与客户端衔接胜利时,服务端会监听到connection
和connect
事宜(connection与connect同义), 客户端会监听到connect
事宜, 断开衔接时服务端的对应到客户端的socket与客户端均会均会监听到disconnect
事宜
服务端代码
let server = require('http').Server()
let io = require('socket.io')(server)
server.listen(3000);
io.on('connection', socket => {
console.log('connect')
socket.on('disconnect', () => {
console.log('disconnect')
})
socket.disconnect()
})
运转后打印
connect
disconnect
客户端代码
let socket = io('http://localhost:3000')
socket.on('connect', () => {
console.log('connect')
})
socket.on('disconnect', () => {
console.log('disconnect')
})
运转后打印
connect
disconnect
传输数据
服务器与客户端的socket是一个关联的EventEmitter对象,客户端socket派发的事宜能够通以被服务端的socket吸收,服务器端socket派发的事宜也能够被客户端接收。基于这类机制,能够完成双向交流。
如今模仿如许一种状况:客户端不断发送随机数,当随机数大于0.95时,服务端延时1s后向客户端发送正告以及正告次数
服务端代码
let server = require('http').Server()
let io = require('socket.io')(server)
server.listen(3000);
io.on('connection', socket => {
socket.on('random', value => {
console.log(value)
if (value > 0.95) {
if (typeof socket.warning === 'undefined') socket.warning = 0
setTimeout(() => {
socket.emit('warn', ++socket.warning)
}, 1000)
}
})
})
socket对象能够用来存储状况信息和自定义数据,如socket.warning
客户端代码
let socket = io('http://localhost:3000')
let interval = setInterval(() => {
socket.emit('random', Math.random())
}, 500)
socket.on('warn', count => {
console.log('warning count: ' + count)
})
socket.on('disconnect', () => {
clearInterval(interval)
})
传输流
socket.io能够处置惩罚流
服务端代码
io.on('connection', function (socket) {
let stream = ss.createStream()
ss(socket).emit('script', stream)
fs.createReadStream(__filename).pipe(stream)
})
客户端代码
let socket = io('http://localhost:3000')
ss(socket).on('script', stream => {
let buffer = ''
stream.on('data', data => {
buffer += data.toString()
})
stream.on('end', () => {
console.log(buffer)
})
})
更多文章的目录在这里