简体   繁体   English

Ruby TCPSocket read_all

[英]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. 是否有一种方法可以像read_all一样使用,而不是使用TCPSocket.read(no_of_bytes),因此可以简单地使用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. 我先通过YAML :: dump'对象发送对象,然后再发送它们,但是我不知道一种以字节为单位获取对象大小的方法。 Thanks in advance, ell. 预先感谢,ell。 Oh and I am very, very new to any form of network programming so go easy on me! 哦,我对任何形式的网络编程都非常陌生,所以请放轻松!

使用Ruby无法为您提供帮助,但是对象序列化和网络连接的通常做法是先发送长度,以便您知道要读取的长度,或者使用预定义的分隔符来分隔消息。

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 :) 这是最简单的任务之一:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM