我想在Cowboy中使用MessagePack编码将消息发送到浏览器,但接收到的数据始终为空或无效。我能够从JS向我的cowboy处理程序发送二进制数据,但反之则不行。
我正在使用Cowboy 1.0.4和官方
浏览器在msgpack.min.js内返回错误:
如果我尝试将原始的事件数据输出到控制台,我得到的是这样的内容:
msgpack-erlang
应用程序。 我还为我的浏览器端JavaScript使用msgpack-lite
。
示例:
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};
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);
};
浏览器在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...
如果我尝试将原始的事件数据输出到控制台,我得到的是这样的内容:
ArrayBuffer {}
由于某些原因似乎是空的。我对erlang
和msgpack
都很陌生,不知道出了什么问题。谢谢你的帮助!
event.data
里面有内容吗? - Hynek -Pichi- Vychodilevent.data
返回一个空的ArrayBuffer {}
。 - Constantine EmeraldMastermsgpack:pack(<<"message">>)
。它应该是<<196,7,109,101,115,115,97,103,101>>
。然后可能是在{binary, _}
或者socket.binaryType = 'arraybuffer'
中出了问题。我不知道。你应该能够以这种方式发送普通的二进制数据。 - Hynek -Pichi- Vychodil