服务器(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向我展示带有字节长度且无效载荷的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()
二元接收在铬&amp;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 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]