看完让你彻底搞懂Websocket原理 - 知乎
什么是webSocket?
H5的一种新协议(websocket协议本质上是一个基于tcp的协议)webScocket是一个持久化协议
WebSocket核心:告诉服务端我是webSocket协议
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13复制代码
什么是持久化协议?
1.客户端发起HTTP请求,经过3次握手建立TCP连接,HTTP请求里放WebSocket的版本号等信息。2.服务器收到客户端握手请求后,返回数据。这样协议就升级为WebSocket,服务端不用依附于客户端就可以主动推送信息给客户端(此时服务器就不再需要客户端发起请求,再响应请求了,可以主动推送信息给客户端了)
步骤:
- 初始化WebSocket
- 实例化WebSocket
- 建立连接
- 监听WebSocket信息
- 关闭WebSocket
- 建立连接成功后执行send发送消息
- 数据接收
- 建立连接失败后重新发送
- 关闭
<a-button
v-if="isOneStepLogin"
size="large"
type="danger"
class="login-button"
:block="true"
@click="initWebSocket">
域账户一键登录(Beta)
</a-button>
<a v-if="notInstallPlugin" download="ssoplugin.zip" style="lineheight:1.5em;display:block;margin-top: 5px;" href="http://58f80dc82f4b0dd9.paas.gwm.cn/api/v1/public/user/lishuaipeng/bucket/datacenter/file/ssoplugin.zip?key=fa74ecb925518c24">
点击下载插件(仅支持windows系统下,域账户登录用户)
</a>
data(){
return{
notInstallPlugin: false,
wsUri: 'ws://127.0.0.1:8080',
}
}
beforeMount() {
this.initWebSocket()
},
destroyed() {
// 离开路由之后断开 websocket 连接
this.websock.close()
},
methods:{
initWebSocket () {
// 初始化weosocket
if (window['WebSocket']) {
if (this.websock !== null && this.websock.readyState === 1) {
this.websock.send('ad')
return
}
// 实例化 WebSocket
this.websock = new WebSocket(this.wsUri)
// 监听 WebSocket 消息
this.websock.onmessage = this.websocketonmessage
// 监听 WebSocket 错误信息
this.websock.onerror = this.websocketonerror
// 监听 WebSocket 连接
this.websock.onopen = this.websocketonopen
this.websock.onclose = this.websocketclose
} else {
this.$showNotification('error', '信息', '当前浏览器不支持websocket协议,建议使用Chrome浏览器')
}
},
// 连接建立之后执行send方法发送数据
websocketonopen () {
console.log('链接成功!')
this.websock.send('ad')
},
// 数据发送
send () {
this.websock.send('ad')
},
// 连接建立失败重连
websocketonerror () {
this.notInstallPlugin = true
console.log('链接异常!')
this.$showNotification('error', '信息', '请检查一键登录插件安装情况')
},
// 数据接收
websocketonmessage (e) {
const data = e.data
if (data === '获取失败') {
this.$showNotification('error', '信息', '数据获取异常,请检查插件状态或使用账号密码登录')
} else {
const {
ADLogin
} = this
ADLogin({})
.then((res) => this.loginSuccess(res))
.catch(err => this.requestFailed(err))
.finally(() => {
})
}
},
// 关闭
websocketclose(e) {
console.log('WebSocket 断开连接', e)
}
}