gpt4 book ai didi

javascript - 访问 WebSocket 时出现 InvalidStateError

转载 作者:搜寻专家 更新时间:2023-10-30 22:16:42 25 4
gpt4 key购买 nike

我已经使用 vue-cli 工具配置了一个简单的 Vue 项目:

vue init webpack my-project

现在我想在页面呈现之前通过网络套接字发送一些信息。由于我不想将此逻辑绑定(bind)到 Vue 组件,因此我有一个不同的 js 文件(名为 ws.js 并基于 this ):

import Vue from 'vue'

const websocket = new WebSocket('ws://localhost:1234')

const emitter = new Vue({
name: 'emitter',
methods: {
send (message) {
websocket.send(JSON.stringify(message))
}
}
})

export default emitter

当页面加载时,我使用 emitter 对象发送一些信息:

<template>
<div class="hello">
TEST
</div>
</template>

<script>
import emitter from '../ws/ws'
export default {
name: 'HelloWorld',
beforeMount () {
emitter.send('Hello')
}
}
</script>

我在 Firefox 控制台中收到此错误:

[Vue warn]: Error in beforeMount hook: "InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable"

found in

---> at src/components/HelloWorld.vue at src/App.vue

我做错了什么?我应该附加到不同的事件监听器而不是 beforeMount() 吗?如果我注释掉与 WebSocket 相关的行,错误就会消失:

import Vue from 'vue'

// const websocket = new WebSocket('ws://localhost:1234')

const emitter = new Vue({
name: 'emitter',
methods: {
send (message) {
// websocket.send(message)
}
}
})

export default emitter

最佳答案

在发送任何消息之前,我需要在套接字处于就绪状态之前对其进行写入,所以 based in this answer我已将 ws.js 更改为:

import Vue from 'vue'

const websocket = new WebSocket('ws://localhost:1234')

// Make the function wait until the connection is made...
function waitForSocketConnection (socket, callback) {
setTimeout(
function () {
if (socket.readyState === 1) {
console.log('Connection is made')
if (callback != null) {
callback()
}
} else {
console.log('wait for connection...')
waitForSocketConnection(socket, callback)
}
}, 5) // wait 5 milisecond for the connection...
}

function sendWaiting (msg) {
waitForSocketConnection(websocket, () => {
console.log('Sending ' + msg)
websocket.send(msg)
console.log('Sent ' + msg)
})
}

const emitter = new Vue({
name: 'emitter',
methods: {
send (message) {
sendWaiting(message)
}
}
})

export default emitter

现在,在发送任何消息之前,应用程序会检查 WebSocket 是否准备就绪并发送它,否则它会每 5 毫秒重新检查一次,直到准备就绪。

关于javascript - 访问 WebSocket 时出现 InvalidStateError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50943020/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com