Ell
Ell

Reputation: 4358

Ruby TCPSocket read_all

Is there a method that can act like read_all, as in instead of using TCPSocket.read(no_of_bytes), one can simply TCPSocket.read_all. I am sending objects first by YAML::dump'ing them then sending them but I don't know a way to get their size in bytes. Thanks in advance, ell. Oh and I am very, very new to any form of network programming so go easy on me!

Upvotes: 0

Views: 1233

Answers (2)

chmod222
chmod222

Reputation: 5722

I doubt there is such a function. HOWEVER! Writing it really is the easiest part. I'm going to have to make this language agnostic, because it's a long time since I've written any ruby code, but in pseudocode it is basically like this

def read_all(s)
   buffer = ""

   while (tmp = s.recv(128))
      if tmp == end_of_file
         break
      end

      buffer = buffer + tmp
   end

   return buffer
 end

Done. Looping and receiving until there is no more data available. That's one of the easiest tasks :)

Upvotes: 1

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84159

Can't help you with Ruby, but the usual practice with object serialization and networking is to either send the length first, so you know how much to read, or use a pre-defined delimiter to separate messages.

Upvotes: 2

Related Questions