浏览器
很显然,要支持WebSocket通信,浏览器得支持这个协议,这样才能发出ws://xxx的请求。目前,支持WebSocket的主流浏览器如下:
- Chrome
- Firefox
- IE >= 10
- Sarafi >= 6
- Android >= 4.4
- iOS >= 8
属性
WebSocket.onclose用于指定连接关闭后的回调函数WebSocket.onerror用于指定连接失败后的回调函数WebSocket.onmessage用于指定当从服务器接受到信息时的回调函数WebSocket.onopen用于指定连接成功后的回调函数
方法
WebSocket.close([code[, reason]])关闭当前链接WebSocket.send(data)向服务器发送数据
特点
- 建立在TCP协议之上,服务端的实现比较容易;
- 与HTTP协议有着良好的兼容性。默认端口也是80和443,并且握手阶段采用HTTP协议,因此握手时不容易屏蔽,能通过各种HTTP代理服务器;
- 数据格式比较轻量,性能开销小,通信高效;
- 可以发送文本,也可以发送二进制数据
- 没有同源限制,客户端可以与任意服务器通信
- 协议标识符是 WS(如果加密,则为WSS),服务器网址就是URL
用法
export default {
data() {
return {
websock: null
}
},
created() {
this.threadPoxi() //调用方法
},
destroyed() {
//页面销毁时关闭长连接
this.websocketclose()
},
methods: {
threadPoxi(){ // 实际调用的方法
//参数
const agentData = "mymessage";
//若是ws开启状态
if (this.websock.readyState === this.websock.OPEN) {
this.websocketsend(agentData)
}
// 若是 正在开启状态,则等待300毫秒
else if (this.websock.readyState === this.websock.CONNECTING) {
let that = this;//保存当前对象this
setTimeout(function () {
that.websocketsend(agentData)
}, 300);
}
// 若未开启 ,则等待500毫秒
else {
this.initWebSocket();
let that = this;//保存当前对象this
setTimeout(function () {
that.websocketsend(agentData)
}, 500);
}
},
initWebSocket() {
//初始化weosocket
const wsuri = 'ws://...' //ws地址(后端提供)
this.websock = new WebSocket(wsuri)
this.websock.onmessage = this.websocketonmessage
this.websock.onopen = this.websocketonopen
this.websock.onerror = this.websocketonerror
this.websock.onclose = this.websocketclose
},
websocketonopen() {
//连接建立之后执行send方法发送数据
this.websocketsend(this.user)
console.log('WebSocket连接成功')
},
websocketonerror(e) {
//连接建立失败重连
this.initWebSocket()
},
websocketonmessage(e) {
//数据接收
const redata = JSON.parse(e.data)
console.log(redata.value)
},
websocketsend(Data) {
//数据发送
this.websock.send(Data)
},
websocketclose(e) {
//关闭
console.log('断开连接', e)
}
}
}