简体   繁体   中英

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. And in the process of receiving data through onmessage, the data came into Blob, not Json or string. I couldn't find a way to change this Blob to Json, so I posted a question here.

Is there any way to receive the data in string or Json? Or how to change Blob to string or Json.

The server is written in c++ and sent as a string.

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. When a text message is received by Javascript, it is deserialised as a string; 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).

The fact that you got a Blob indicates that the server sent a binary message. This is unusual for a JSON message, so either the server is very unusual, or the protocol is not based on JSON.

In any case, you can convert r data into a string by calling the async .text() method:

let data = await event.data.text();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM