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:
- Send a keep-alive from the client and close when you do not receive it or
- 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
Grouped Collection Select Alphabetical Order Rails
How to Deal with App_Key and App_Secret (Dropbox API)
Listing Directories at a Given Level in Amazon S3
Displaying a Polygon with Gmaps4Rails
How to Use Escape Characters in Strings
How to Run All Ruby Scripts with Warnings
Ruby Gems Won't Load Even Though Installed
Custom Filtering of Parameters in Rails 3 Using Config.Filter_Parameters
Could Not Find Rake-10.1.0 in Any of the Sources
Yielding in an Anonymous Block
How to Share State Between Scenarios Using Cucumber
Grabbing Snapshots from Webcams in Ruby
Ror - How to Remove Rails 4.1.1 Version
Is There a Bug in Ruby Lookbehind Assertions (1.9/2.0)
Setting Mime Type for .Ogv Files in Rails Development Environment
Is It Necessary to Close Stringio in Ruby