gpt4 book ai didi

javascript - 为什么 JS 客户端不从服务器接收二进制文件?

转载 作者:行者123 更新时间:2023-11-30 08:24:40 25 4
gpt4 key购买 nike

服务器( 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

客户端(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.

但是! 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()

二进制接收在 chromium 和 firefox 中不起作用。

最佳答案

在客户端使用 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]

匹配从 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]

关于javascript - 为什么 JS 客户端不从服务器接收二进制文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47531467/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com