From: Robert Klemme Date: 2012-08-20T18:02:22+09:00 Subject: Re: TCPserver how to signal EOT On Sun, Aug 19, 2012 at 1:03 PM, tammy roberts wrote: > Hi I am writing some networking code and am having a heck of a time > figuring out how to break on EOT. > This is only one of > many ways I have tried, client.recvfrom does not seem to return 0 or -1 > when no more data is to be sent, it also does not seem to return an > empty string. Then it probably blocks. > Pretty much the only way I have gotten this to work is by > looping client.recvfrom and then breaking if the character at -1 in what > it gets is the ASCII control character for EOT. Unfortunately I can not > use that because when I send random binary data there is a chance it > will end on EOT without it being a control character. I have seen recvfrom mainly used with UDP sockets and I am not sure whether it blocks. Apparently you want blocking behavior since you create a thread per connection. > Surely there is some easy way to do this, but none of the Ruby > documentation mentions anything about how to and most of the examples do > not even have recv in a loop for some reason. Yes, just use Ruby's ways to use custom line delimiters. Here's one working way: DELIMITER = "\x04".freeze loop do Thread.new(server.accept) do |client| printf "Client %p START\n", client client.each_line DELIMITER do |msg| printf "msg len = %4d msg: %p bytes: %p\n", msg.length, msg, msg.unpack('C*').map {|i| "%02x" % i} msg.chomp! DELIMITER printf "msg len = %4d msg: %p bytes: %p\n", msg.length, msg, msg.unpack('C*').map {|i| "%02x" % i} end printf "Client %p STOP\n", client end end Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/