我创建了一个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
我得到的事件:
{ "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","target": { "binaryType": "blob","type": "message" }
解决方法
好的,我找到了解决方案!我必须读取带有FileReader的Blob数据:
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
或者,在ES2015中:
// Create socket socket = new WebSocket("wss://example.org/ws"); socket.binaryType = "blob"; // Log socket opening and closing socket.addEventListener("open",event => { console.log("Websocket connection opened"); }); socket.addEventListener("close",event => { console.log("Websocket connection closed"); }); // Handle the message socket.addEventListener("message",event => { if (event.data instanceof Blob) { reader = new FileReader(); reader.onload = () => { console.log("Result: " + reader.result); }; reader.readAsText(event.data); } else { console.log("Result: " + event.data); } });