WebSocket 可以实现浏览器和服务器之间双向通信的持久性连接。使用此 API,您可以向服务器发送消息并接收事件驱动的响应,而无需通过轮询服务器的方式以获得响应。还可以实现实时推送和跨域。
WebSocket 支持传输的数据格式为:字符串、Blob、ArrayBuffer、ArrayBufferView。
对不支持 WebSocket 的低版本浏览器,可以使用 Socket.io 第三方插件。
兼容性
IE9+
语法
var socket = new WebSocket(url [, protocols]); // 返回一个 WebSocket 对象
- url: websocket服务器地址。网页协议和websocket协议最好对应,http 对应 ws,https 对应 wss。
- protocols: 一个协议字符串或者一个包含协议字符串的数组。这些字符串用于指定子协议,这样单个服务器可以实现多个 WebSocket 子协议(例如,您可能希望一台服务器能够根据指定的协议(protocol)处理不同类型的交互)。如果不指定协议字符串,则假定为空字符串。
使用 new WebSocket() 示例
const socket = new WebSocket('ws://localhost:8080');
// socket.binaryType = 'arraybuffer'; // 如果传输的是二进制数据,要定义二进制数据类型
socket.onopen = function (event) {
const data = JSON.stringify({msg: 'Hello'});
socket.send(data);
};
socket.onmessage = function (event) {
try {
const data = JSON.parse(event.data);
} catch (error) {
}
};
socket.onerror = function (event) {
console.log('出错啦!', event);
};
socket.onclose = function () {
console.log('websocket关闭');
};
关闭连接前最好检查一下 socket.bufferedAmount 是否为0,以防还有数据要传输。
使用 socket.io 示例
npm i -S socket.io socket.io-client
Client
mySocket.js (封装 socket,方便被emit调用)
import io from 'socket.io-client';
/**
* Socket 对象
**/
class mySocket {
constructor() {
this.socket = null;
}
/**
* socket 连接 connect
* @param {String} ip
**/
connect(ip [, options]) {
this.socket = io.connect(ip, {
reconnection: true,
reconnectionDelay: 500,
reconnectionAttempts: 5,
timeout: 40000,
path: '/notice',
query: {}
})
}
/**
* socket 监听 on
* @param {String} type
* @param {Function} func
**/
on(type, func) {
if (this.socket) {
this.socket.on(type, func);
} else {
throw new Error('socket 未连接');
}
}
/**
* socket 事件触发 emit
* @param {String} type
* @param {Object} params
**/
emit(type,params) {
if (this.socket) {
this.socket.emit(type, params);
} else {
throw new Error('socket 未连接');
}
}
/**
* socket 关闭 close
**/
close() {
this.socket && this.socket.close();
}
}
export default new mySocket();
index.js
import socket from 'utils/mySocket';
Http.get(Api.getSocketInfo).then((res) => {
// res.data = 192.118.10.80?JSESSIONID=b21205400b108b16e
const socketUrl = window.location.protocol + '//' + res.data + '&shopId=1;
// 连接(socket连接的地址可以请求后台获取)
socket.connect(socketUrl);
// socket 连接成功
socket.on('connect', () => {
console.log('socket连接成功,URL:', socketUrl);
});
// socket 消息接收
socket.on('msgEvent', (data) => {
data = JSON.parse(data);
// to do sth ...
// socket 发送消息
try {
socket.emit('emitMessage', {
shopId: '1',
orderId: '32542321'
});
} catch (e) {
throw new Error(e);
}
}
}
Server
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(8001, ()=>{
console.log('webSocket server listening on port 8001')
});
app.get('/', (req, res)=>{
res.sendFile(__dirname + '/index.html');
});
io.on('connection', (socket)=>{
socket.emit('news', { hello: 'world' });
socket.on('otherEvent', (data)=>{
console.log(data);
});
});
参考
- Introduction | Socket.IO
- WebSocket - Web API 接口参考 | MDN