[英]Problems with Blob acquisition when receiving data through a web-socket
In the process of communicating with the server using a web socket, the data is handed over to the server to Json.在使用web socket与服务器通信的过程中,将数据交给服务器交给Json。 And in the process of receiving data through onmessage, the data came into Blob, not Json or string.而且在通过onmessage接收数据的过程中,数据进来的是Blob,不是Json,也不是string。 I couldn't find a way to change this Blob to Json, so I posted a question here.我找不到将此 Blob 更改为 Json 的方法,所以我在这里发布了一个问题。
Is there any way to receive the data in string or Json?有没有办法接收字符串或Json 中的数据? Or how to change Blob to string or Json.或者如何将 Blob 更改为字符串或 Json。
The server is written in c++ and sent as a string.服务器是用 C++ 编写的,并作为字符串发送。
useEffect(() => {
//var socket = new WebSocket("ws://172.30.1.50:65432/websocket");
const socket = new WebSocket("ws://ip:port/websocket"); //For convenience, I wrote down ip and port.
socket.Type = "blob"
socket.onopen = function (event) {
socket.send(JSON.stringify({ 'CMD': 'test' }))
console.log("connetion?");}
socket.close
socket.onmessage = function (event) {
console.log((event.data))
}, []})
The WebSocket protocol supports two kinds of data messages: text and binary. WebSocket 协议支持两种数据消息:文本和二进制。 When a text message is received by Javascript, it is deserialised as a string;当 Javascript 收到一条短信时,它被反序列化为一个字符串; when a binary message is received, it is deserialised as either an ArrayBuffer or a Blob, depending on the value of the websocket's binaryType
property (the default is to return a Blob).当收到二进制消息时,它会反序列化为 ArrayBuffer 或 Blob,具体取决于 websocket 的binaryType
属性的值(默认返回 Blob)。
The fact that you got a Blob indicates that the server sent a binary message.你得到一个 Blob 的事实表明服务器发送了一个二进制消息。 This is unusual for a JSON message, so either the server is very unusual, or the protocol is not based on JSON.这对于 JSON 消息来说是不寻常的,所以要么服务器非常不寻常,要么协议不是基于 JSON 的。
In any case, you can convert r data into a string by calling the async .text()
method:在任何情况下,您都可以通过调用 async .text()
方法将 r 数据转换为字符串:
let data = await event.data.text();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.