Socket.recv works but not gets or read?

Posted by Earlz on Stack Overflow See other posts from Stack Overflow or by Earlz
Published on 2010-06-07T04:43:39Z Indexed on 2010/06/07 4:52 UTC
Read the original article Hit count: 277

Filed under:
|
|

Hello I've been messing around with Sockets in Ruby some and came across some example code that I tried modifying and broke. I want to know why it's broken.

Server:

require "socket"  
dts = TCPServer.new('127.0.0.1', 20000)  
loop do  
  Thread.start(dts.accept) do |s|  
  print(s, " is accepted\n")  
  s.write(Time.now)  
  print(s, " is gone\n")  
  s.close  
  end  
end  

Client that works:

require 'socket'  
streamSock = TCPSocket.new( "127.0.0.1", 20000 )  
streamSock.print( "Hello\n" )  
str = streamSock.recv( 100 )  
print str  
streamSock.close 

Client that is broken

require 'socket'  
streamSock = TCPSocket.new( "127.0.0.1", 20000 )  
streamSock.print( "Hello\n" )  
str=streamSock.read #this line modified
print str  
streamSock.close 

I know that the streamSock.print is unnecessary (as well as the naming scheme being non-ruby) but I don't understand why read doesn't work while recv does, Why is this?

© Stack Overflow or respective owner

Related posts about ruby

Related posts about networking