[英]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) 客户端(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. Console.log向我展示了具有字节长度且没有任何有效载荷的ArrayBuffer(13)。
But! 但! Python client ( https://github.com/websocket-client/websocket-client ) works fine. 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()
Binary receiving doesn't work in chromium & firefox. 二进制接收不适用于铬和Firefox。
Use ws.binaryType = "arraybuffer"
and convert it to Uint8Array
on a client: 使用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]
which matches the byte array sent from Crystal server: 匹配从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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.