我试图使用JS和VUE从websocket接收数据,但我遇到了问题:
要接收数据,我使用代码:
created() {
console.log('Starting Connection to WebSocket')
this.connection = new WebSocket('ws://127.0.0.1:8080/live')
// this.connection = new WebSocket('ws://echo.websocket.org')
this.connection.onopen = function (event) {
console.log(event)
console.log('Success')
}
this.connection.onmessage = webSocketOnMSG
},并试图解析blob:
function webSocketOnMSG(msg) {
if (typeof (msg.data) === 'string') {
jsonMSG(msg.data)
return
}
bytes = new Uint8Array(msg.data)
console.log('!!!BYTE', bytes)
type = bytes[0]
switch (type) {
}
}和console.log('!!!BYTE', bytes)
显示:
Blob {size: 187086, type: ""}但应该是:
ArrayBuffer(187086)正因为如此,type是未定义的。
但我有其他(明确的js版本)没有VUE,在那里它工作的很好。
你能帮帮我吗,怎么了?
发布于 2021-04-23 11:49:23
假设msg.data确实是一个blob,您可以使用blob的arrayBuffer方法将该blob读入一个ArrayBuffer,然后从该缓冲区生成一个Uint8Array。注意,arrayBuffer返回一个承诺;读取blob内容是一个异步操作。
示例:
function webSocketOnMSG(msg) {
if (typeof msg.data === "string") { // `typeof` isn't a function, no need for `()`
jsonMSG(msg.data);
return;
}
// Assuming `msg.data` really is a `Blob`, then:
msg.data.arrayBuffer()
.then(buf => new Uint8Array(buf))
.then(bytes => {
console.log('!!!BYTE', bytes);
const type = bytes[0];
switch (type) {
// ...
}
})
.catch(error => {
// ...handle/report error...
});
}https://stackoverflow.com/questions/67229333
复制相似问题