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
One way of sending integer byte values would be to use array.pack.
socket.write [0x02].pack("C")
1 Comment
Mark Wilkins
@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).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
cam
write or print would be more appropriate than puts in this instance, if he's looking to write a byte to the socket.