3

How can I write a byte to a socket in ruby? I specifically mean how can I write something like 0x02 to a socket. Thanks.

2 Answers 2

5

One way of sending integer byte values would be to use array.pack.

socket.write [0x02].pack("C")
Sign up to request clarification or add additional context in comments.

1 Comment

@mu is too short: Right ... it should be write. Thanks. I was thinking of the packing part and not the putting it on the wire part. The puts call (I believe) adds \n to the end of it (resulting in two bytes).
4

Something like this ?

require 'socket'               # Get sockets from stdlib

server = TCPServer.open(2000)  # Socket to listen on port 2000
loop {                         # Servers run forever
  client = server.accept       # Wait for a client to connect
  client.write("\x02")
  client.close                 # Disconnect from the client
}

1 Comment

write or print would be more appropriate than puts in this instance, if he's looking to write a byte to the socket.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.