为什么JS-client不从服务器接收二进制文件?

1 javascript websocket crystal-lang

服务器(水晶)

require "http"

module Network
    class WebSocket < HTTP::WebSocketHandler
        HANDLERS = [] of HTTP::Handler
        def initialize (@path : String, &@proc : HTTP::WebSocket, HTTP::Server::Context -> Nil)
            HANDLERS << self
        end

        def self.run (host : String = "::", port : Int32 = 3030)
            puts "Run server on ws://[#{host}]:#{port}"
            HTTP::Server.new(host, port, HANDLERS).listen
        end
    end
end

Network::WebSocket.new "/" do |socket|
    socket.send("Hello From Binary!".to_slice)
end

Network::WebSocket.run
Run Code Online (Sandbox Code Playgroud)

客户端(JavaScript的)

ws = new WebSocket("ws://[2a01:4f8:xx:xx::xx]:3030/")
ws.onmessage = (message) => {
    console.log(message.data)
}
Run Code Online (Sandbox Code Playgroud)

Console.log向我展示了字节长度且没有任何有效负载的ArrayBuffer(13).

但!Python客户端(https://github.com/websocket-client/websocket-client)工作正常.

from websocket import create_connection
ws = create_connection("ws://[::]:3030")
print("Receiving...")
result =  ws.recv()
print("Received '%s'" % result)
ws.close()
Run Code Online (Sandbox Code Playgroud)

二进制接收在chrome和firefox中不起作用.

Vit*_*upt 5

使用ws.binaryType = "arraybuffer"并将其转换Uint8Array为客户端:

new Uint8Array(message.data) // => [72, 101, 108, 108, 111, 32, 70, 114, 111, 109, 32, 66, 105, 110, 97, 114, 121, 33]
Run Code Online (Sandbox Code Playgroud)

它匹配从Crystal服务器发送的字节数组:

"Hello From Binary!".to_slice # => Bytes[72, 101, 108, 108, 111, 32, 70, 114, 111, 109, 32, 66, 105, 110, 97, 114, 121, 33]
Run Code Online (Sandbox Code Playgroud)