在此套接字示例中,“ line = s.gets”是什么意思?

时间:2018-09-27 21:07:21

标签: ruby sockets

require 'socket'

s = TCPSocket.new('localhost', 2000)

while line = s.gets # Read lines from socket
  puts line         # and print them
end

s.close             # close socket when done

我一般是Ruby和套接字的新手;我从Ruby Sockets文档页面获得了这些代码作为其示例之一。我了解line = s.gets片段以外的所有内容。何时调用gets是获取输入还是Socket类的方法?谁能给我一个解释?谢谢!

2 个答案:

答案 0 :(得分:2)

文档中的示例可以解释为

  

打开一个到本地主机端口2000的TCP套接字。

     

逐行读取;在阅读打印内容的同时。

     

如果没有要读取的内容,请关闭套接字。

基本上,我认为整个表达方式

while line = s.gets
  puts line
end

可能会让Ruby新手感到困惑。

上面的代码段使用方法s从套接字gets读取内容。该method返回“行”(字符串),包括尾随符号\n。该结果将分配给line变量。

line = s.gets表达式似乎不是一个比较。这是任务。 Ruby中的每个分配都返回一个已分配的值。因此,此操作的结果是一个字符串,由gets返回。

通过while语句求值时,字符串将转换为boolean。任何字符串,即使是空字符串,都被视为true,因此将执行带有puts line的块。

由于这是一个while循环,因此它将一次又一次地重复,直到gets方法返回nil,这意味着没有任何内容可以从套接字读取(传输完成)。 )。

答案 1 :(得分:1)

s = TCPSocket.new 'localhost', 2000 # Opens a TCP connection to host


while line = s.gets # Read the socket like you read any IO object.
                    # If s.gets is nil the while loop is broken
      puts line     # Print the object (String or Hash or an object ...)
end

就像:

客户端

#Init connection
   Client.send("Hello") #The client send the message over socket(TCP/IP)
#Close connection

服务器端

#Init connection
    while line = s.gets # The client get the message sended by the client and store it in the variable line

        puts line  # => Hello
    end
#Close connection