How to send bytes by UDP?

I thought I’d whip up a simple quick command line program to send bytes by UDP to test some other software. Turns out not to be as quick as I was hoping. The server.send method has trouble compiling.

In /usr/lib/crystal/socket.cr:298:26
 298 | evented_send(message.to_slice, "Error sending datagram") do |slice|
                            ^-------
Error: undefined method 'to_slice' for Array(UInt8)

The source code, stripped to essentials, is:

  alias Byte = UInt8
  cat48data : Array(Byte)  = Byte[ 11, 22, 33, 44 ]

  server = UDPSocket.new
  server.bind "192.168.11.23", 

  while command!='q' 
    server.send cat48data
  end

The easiest solution is probably to use a byte slice instead of an array: Bytes[11, 22, 33, 44]

Also if you need something similar to an array in that you can easily manipulate it then IO::Memory is super useful and it has a to_slice method. Also deals with endianness

1 Like