Reputation: 678
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
I'm a newcomer to Ruby and sockets in general; I got this code from the Ruby Sockets documentation page as one of their examples. I understand everything except the line = s.gets
snippet. When gets is called is it getting input or is a method of the class Socket? Can anyone please give me an explanation? Thanks!
Upvotes: 0
Views: 401
Reputation: 2791
The example from documentation can be explained as
Open a TCP socket to localhost, port 2000.
Read from it line by line; while reading print what was read.
When there is no content left to read, close the socket.
Basically, I think the whole expression
while line = s.gets
puts line
end
can be confusing for Ruby newcomers.
The code snippet above reads content from socket s
with method gets
. This method returns a "line" (a string), including trailing symbol \n
. That result is assigned to line
variable.
line = s.gets
expression is not a comparison as it may seem; it's assignment. Every assignment in Ruby returns a value, which is assigned. So the result of this operation is a string, returned by gets
.
When evaluated by while
statement, string is converted to boolean
. Any string, even empty one, is considered as true
, so block with puts line
is executed.
Since it is a while
loop, it will be repeated again and again, until gets
method returns nil
, which means there is nothing left to read from the socket (transfer complete).
Upvotes: 2
Reputation: 96
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
Its like :
Client side
#Init connection
Client.send("Hello") #The client send the message over socket(TCP/IP)
#Close connection
Server side
#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
Upvotes: 1