Con*_*ter 7 javascript erlang websocket messagepack cowboy
我正在尝试通过WebSocket将来自Cowboy的MessagePack编码消息发送到浏览器,并且接收的数据始终为空或无效.我能够将JS中的二进制数据发送给我的牛仔处理程序,但反之亦然.我正在使用Cowboy 1.0.4和官方msgpack-erlang应用程序.我也msgpack-lite用于我的浏览器中的JavaScript.
例子:
websocket_handler:
websocket_handle({text, <<"return encoded">>}, Req, State) ->
%% sends encoded message to client. Client is unable to decode and fails
{reply, {binary, msgpack:pack(<<"message">>)}, Req, State};
websocket_handle({binary, Encoded}, Req, State) ->
%% Works as expected
lager:info("Received encoded message: ~p", [msgpack:unpack(Encoded)]),
{ok, Req, State};
Run Code Online (Sandbox Code Playgroud)
JS:
var host = "ws://" + window.location.host + "/websocket";
window.socket = new WebSocket(host);
socket.binaryType = 'arraybuffer';
socket.onmessage = function(event) {
var message = msgpack.decode(event.data);
console.log(message);
};
Run Code Online (Sandbox Code Playgroud)
浏览器在msgpack.min.js中返回错误:
Error: Invalid type: undefined
...ion n(t){var r=i(t),e=f[r];if(!e)throw new Error("Invalid type: "+(r?"0x"+r.toSt...
Run Code Online (Sandbox Code Playgroud)
如果我尝试将原始event.data输出到控制台,这是我得到的:
ArrayBuffer {}
Run Code Online (Sandbox Code Playgroud)
由于某种原因,它似乎是空的.我是新既erlang和msgpack,不知道什么错误.谢谢你的帮助!
找到了我的问题的原因.我尝试在客户端上解码消息的方式是错误的:
socket.onmessage = function(event) {
var message = msgpack.decode(event.data);
console.log(message);
};
Run Code Online (Sandbox Code Playgroud)
正确的方式:
socket.onmessage = function(event) {
var raw_binary_data = new Uint8Array(event.data);
var message = msgpack.decode(raw_binary_data);
console.log(message);
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1609 次 |
| 最近记录: |