如何从不是图像的WebSocket读取BLOB数据

时间:2014-01-24 17:01:53

标签: javascript websocket coffeescript blob

我创建了一个WebSocket连接到我的网络服务器以接收一些数据。但是,当我在onmessage函数中记录我收到的事件时,我无法看到数据的真实内容。

当我将我的Chrome浏览器v32打开的网络连接复制为curl命令并在我的操作系统控制台上运行时,一切正常。所以我认为我的WebSocket设置必定是错误的。 event.data对象是Blob的实例。

这是我的代码(实际上是CoffeeScript,但很容易理解)

socket = new WebSocket "wss://myserverurl/some-endpoint"

socket.onopen = (event) ->
    console.log 'Connection opened (WebSocket)'

socket.onclose = (event) ->
    console.log 'Connection closed (WebSocket)'
    code = event.code
    reason = event.reason
    wasClean = event.wasClean

socket.onmessage = (event) ->
    console.log JSON.stringify event

我得到的event

{
    "ports": [],
    "data": {
        "type": "",
        "size": 594
    },
    ...
    "cancelBubble": false,
    "returnValue": true,
    "srcElement": {
        "binaryType": "blob",
        "extensions": "",
        "protocol": "",
        "onerror": null,
        "bufferedAmount": 0,
        "readyState": 1
    },
    "defaultPrevented": false,
    "timeStamp": 1390578698613,
    "cancelable": false,
    "bubbles": false,
    "eventPhase": 2,
    "currentTarget": {
        "binaryType": "blob",
        "extensions": "",
        "protocol": "",
        "onerror": null,
        "bufferedAmount": 0,
        "readyState": 1
    },
    "target": {
        "binaryType": "blob",
        "extensions": "",
        "protocol": "",
        "onerror": null,
        "bufferedAmount": 0,
        "readyState": 1
    },
    "type": "message"
}

2 个答案:

答案 0 :(得分:10)

好的,我找到了解决方案!我必须阅读带有Blob的{​​{1}}数据:

FileReader

或者,在ES2015中:

socket = new WebSocket 'wss://myserverurl/some-endpoint'
socket.binaryType = 'blob'

socket.onopen = (event) ->
    console.log 'Connection opened (WebSocket)'

socket.onclose = (event) ->
    console.log 'Connection closed (WebSocket)'
    code = event.code
    reason = event.reason
    wasClean = event.wasClean

socket.onmessage = (event) ->
    if event.data instanceof Blob
        reader = new FileReader()
        reader.onload = ->
            console.log reader.result
        reader.readAsText event.data

答案 1 :(得分:0)

您可以在 JavaScript 中设置 binaryTypeWebSocket,例如:

var socket = new WebSocket(url);
socket.binaryType = "arraybuffer";

或者分别在 CoffeeScript 中

socket = new WebSocket url
socket.binaryType = "arraybuffer"

你会得到 ArrayBuffers 而不是 Blobs。通过 new Uint8Array(event.data);

将它们转换为 Uint8Array