最近项目在使用websocket,自己研究了下,详细概念性的知识点可以看这里,vue使用websocket可以参考这篇文章,
我这里分享下开发代码,系统理解下使用方法
后面还有一篇文章,是关于websocket的案例的,看这里。
// 初始化websocket
initWebSocket() {
const vm = this
// 创建一个websocket连接
vm.websocket = new WebSocket(process.env.WEBSOCKET_API)
// 看下websocket到底是什么 打印见下文
console.log(vm.websocket)
// websocket建立连接时会触发此方法
vm.websocket.onopen = function() {
// console.log('websocket onopen')
vm.isSocket = true
}
// 客户端接收服务端数据时触发
vm.websocket.onmessage = function(evt) {
const obj = JSON.parse(evt.data)
console.log('websocket请求回来的数据')
console.log(obj)
switch (obj.Command) {
case '8801':
vm.fullscreenLoading = false
if (obj.code === 0) { // 抓拍成功
vm.photograph = obj.Body.photoUrl
vm.getRecordInfo()
vm.$message.success(obj.Msg)
} else {
vm.code = 1
vm.$message.error(obj.Msg)
}
break
case '8300':
// vm.$alert('发送成功!', '提示', {
// confirmButtonText: '确定'
// })
vm.$message.success(obj.Msg)
vm.selectTempId = null
vm.textSend = ''
break
default :
// vm.$alert('失败!', '提示', {
// confirmButtonText: '确定'
// })
vm.$message.error(obj.Msg)
vm.selectTempId = null
vm.textSend = ''
vm.photograph = ''
break
}
}
// 通信发生错误时触发
vm.websocket.onerror = function() { // 如果请求出错则再次连接
vm.initWebSocket()
}
},
}
/**
* 切换处理页面(点击tab切换页面)
* @param index
*/
openPlan(tab, event) {
if (this.activeCode === '1' || this.activeCode === '2' && !this.isSocket) {
console.log('------this.activeCode------')
console.log(this.activeCode)
this.initWebSocket()
}
// 控制台输出 websocket
WebSocket {url: "ws://116.62.56.33:6950/", readyState: 0, bufferedAmount: 0, onopen: null, onerror: null, …}
binaryType: "blob"
bufferedAmount: 0
extensions: ""
onclose: null
onerror: ƒ ()
arguments: [Exception: TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them at Function.invokeGetter (<anonymous>:2:14)]
caller: [Exception: TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them at Function.invokeGetter (<anonymous>:2:14)]
length: 0
name: ""
prototype: {constructor: ƒ}
__proto__: ƒ ()
[[FunctionLocation]]: AlarmInfo.vue?637e:1046
[[Scopes]]: Scopes[3]
onmessage: ƒ (evt)
arguments: [Exception: TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them at Function.invokeGetter (<anonymous>:2:14)]
caller: [Exception: TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them at Function.invokeGetter (<anonymous>:2:14)]
length: 1
name: ""
prototype:
constructor: ƒ (evt)
__proto__: Object
__proto__: ƒ ()
apply: ƒ apply()
arguments: (...)
bind: ƒ bind()
call: ƒ call()
caller: (...)
constructor: ƒ Function()
length: 0
name: ""
toString: ƒ toString()
Symbol(Symbol.hasInstance): ƒ [Symbol.hasInstance]()
get arguments: ƒ ()
set arguments: ƒ ()
get caller: ƒ ()
set caller: ƒ ()
__proto__: Object
[[FunctionLocation]]: <unknown>
[[Scopes]]: Scopes[0]
[[FunctionLocation]]: AlarmInfo.vue?637e:1010
[[Scopes]]: Scopes[3]
onopen: ƒ ()
arguments: (...)
caller: (...)
length: 0
name: ""
prototype: {constructor: ƒ}
__proto__: ƒ ()
[[FunctionLocation]]: AlarmInfo.vue?637e:1006
[[Scopes]]: Scopes[3]
protocol: ""
readyState: 1
url: "ws://116.62.56.33:6950/"
__proto__: WebSocket
<!-- 部分代码 点击图片抓拍,切换tab,可点击拍照-->
<div class="tab-box-header-right">
<el-button type="primary"
@click="camera" // 拍照按钮,上图中未显示
size="small"
v-loading.fullscreen.lock="fullscreenLoading"
element-loading-text="抓拍中,请稍后..."
element-loading-spinner="el-icon-loading"
element-loading-background="rgba(255, 255, 255, 0)">拍照</el-button>
</div>
// 当前方法在用户点击拍照时调用
camera() {
if (this.isSocket) {
this.fullscreenLoading = true
this.subscribe()
}
}
// websocket向服务器发送消息
subscribe() {
const v = this
const data = {
Command: 8801,
CommandType: 'command',
Token: getToken(),
Body: {
data: {
vehicleIds: [this.monInfo.vehicleId],
channelId: this.cameraValue,
deviceType: this.eqValue
}
}
}
// console.log('ws请求参数:', data)
// 判断websocket当前连接状态
if (this.websocket.readyState === 1) {
// 发送数据
this.websocket.send(JSON.stringify(data))
console.log(data)
console.log('消息发送成功')
console.log(v.photograph)
setTimeout(() => {
if (v.code !== 1) {
if (v.photograph !== null && v.photograph !== '') {
v.fullscreenLoading = false
v.$message.error('终端响应超时, 请重试!') // 一个弹窗组件
}
}
}, 10000)
} else {
console.log('websocket信息发送失败')
}
}
// 关闭页面时,关闭websocket连接
destroyed() {
this.websocket.close()
}