Search code examples
javascriptwebsocketcrystal-lang

Why JS-client doesn't receive binary from server?


Server (crystal)

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

Client(JavaScript)

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

Console.log show me ArrayBuffer(13) with byte length and without any payload.

But! Python client (https://github.com/websocket-client/websocket-client) works fine.

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

Binary receiving doesn't work in chromium & firefox.


Solution

  • Use ws.binaryType = "arraybuffer" and convert it to Uint8Array on a client:

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

    which matches the byte array sent from Crystal server:

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