The Crystal Programming Language Forum

Weird issues with websocket binary streams

I don’t believe I am doing anything wrong here, but would appreciate some guidance if I am.
Trying to stream some binary data down a websocket but getting some weird results:

socket = HTTP::WebSocket.new("demos.kaazing.com", "/echo")
socket.on_binary do |data|
  # Data echo'd back is 0, 0, 0, 0 ...
  me = data
  other = String.new(data)

  socket.close
end
# Send the text "testing..." to the far end as binary
socket.stream { |io| io.write "testing...".to_slice }
socket.run

While running that in crystal play i monitored traffic in wireshark and it looks like it’s sending 0’s instead of the data written to the stream

Am I doing something wrong here or should I open an issue?

So it seems if I explicitly define the frame size then this works

socket = HTTP::WebSocket.new("demos.kaazing.com", "/echo")
socket.on_binary do |data|
  # Data echo'd back as expected
  me = data
  other = String.new(data)

  socket.close
end

bindata = Bytes[1,2,3,4,5,6]
socket.stream(true, bindata.size) { |io|
  io.write bindata
}
socket.run
2 Likes

I think it might be a bug in HTTP::WebSocket::Protocol::StreamIO when the buffer is not filled completely there is no flush performed. But even adding a manual flush(final: true) / flush(final: false) as in: socket.stream { |io| io.write "testing...".to_slice; io.flush(final: true) } it does not help.

1 Like