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 套接字文档页面获得了这段代码作为他们的示例之一。我了解除line = s.gets
片段之外的所有内容。何时调用get是获取输入还是Socket类的方法?谁能给我一个解释?谢谢!
文档中的示例可以解释为
打开本地主机端口 2000 的 TCP 套接字。
逐行阅读;阅读时打印阅读的内容。
当没有要读取的内容时,关闭套接字。
基本上,我认为整个表达方式
while line = s.gets
puts line
end
对于 Ruby 新手来说可能会感到困惑。
上面的代码片段使用方法gets
从套接字s
读取内容。此方法返回一个"行"(字符串(,包括尾随符号n
。该结果将分配给line
变量。
line = s.gets
表达不是看起来的比较;它是分配。Ruby 中的每个赋值都会返回一个值,该值被分配。所以此操作的结果是一个字符串,由gets
返回。
当通过while
语句计算时,字符串将转换为boolean
。任何字符串,即使是空的字符串,都被认为是true
的,所以用puts line
块被执行。
由于它是一个while
循环,它将一次又一次地重复,直到gets
方法返回nil
,这意味着没有任何东西可以从套接字读取(传输完成(。
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