Ruby Tcpsocket Write Doesn't Work, But Puts Does

Ruby TCPSocket write doesn't work, but puts does?

Are you sure the problem isn't on the server side? Are you using some method to read that expects a string or something ending in "\n"?

Ruby TCP socket never gets replies

Perhaps you need to add CRLF to the command:

socket.write("HELO " + session + "\r\n")

Sockets in Ruby, how can I asynchronously read and write data through a Socket

Based on Casper's recommendation in the question comments, I changed the proc to use IO.select. It worked as a breese.

The first thing to know is that attempting to read the socket (@socket.recv) when there is no data in its buffer will make the socket "hang" waiting for a new message from the server. This has the the annoying side effect of preventing us from writing to the socket (via separated thread).
So to fix this, the IO.select call would try to read the socked for 2 seconds (the 2 used as last parameter below). When the 2s elapse without data, IO.select returns nil which allowed me to not call @socket.recv when we know it would "hang".

A great side effect is that my while true does not kill the client when there is no data, as IO.select takes 2s to timeout on each loop.

This is the end result:

@socket = TCPSocket.new(localhost, 1234)

def read_data_loop
while true
while IO.select([@socket], nil, nil, 2) && (line = @socket.recv(50))
p line
end
end
end

@buffer_thread = Thread.new { read_data_loop }

@socket.write("send me something!!")

sleep(10)
@buffer_thread.exit

This made the background thread write to the console:

server response
hi there

as these were two messages I had set up on the server.

Ruby: TCPServer is not seeing that client TCPSocket has closed

The only response provided did not work. Attempting to read from the closed socket did not error like I expected it to.

I have come to the conclusion that what I was asking is simply not possible. You must either:

  1. Send a keep-alive from the client and close when you do not receive it or
  2. Face the consequences of not knowing whether or not your writes have
    succeeded.

Personally, I was able to live with 2 since this was for a prototype.



Related Topics



Leave a reply



Submit