Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!nuzba.szn.dk!pnx.dk!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Robert Klemme Newsgroups: comp.lang.ruby Subject: Re: Common way to read/write to/from TCPSocket Date: Fri, 29 Mar 2013 15:23:31 +0100 Lines: 51 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Trace: individual.net dMSTAwoViaNsEEM0vSVxcw06vcqP+wG3iJDpwydjCBfsg/IXQ= Cancel-Lock: sha1:GS6Wgq5iAVmP9vuiqJqJF8e48ZA= User-Agent: Mozilla/5.0 (Windows NT 6.0; WOW64; rv:17.0) Gecko/20130307 Thunderbird/17.0.4 In-Reply-To: X-Antivirus: avast! (VPS 130325-2, 25.03.2013), Outbound message X-Antivirus-Status: Clean Xref: csiph.com comp.lang.ruby:6778 On 29.03.2013 08:00, yspro wrote: > Hi there! I want to know common way to create TCPSocket, write http request and get response. > > My simple function: > > def read_from_sock(host, port) > sock = TCPSocket.new(host, port) > > request = '' > request << "GET / HTTP/1.1\r\n" > request << "Host: #{host}\r\n" > request << "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1\r\n" > request << "\r\n" > > sock.write(request) Try to insert a sock.close_write here. > response = '' > > until sock.eof? > response << sock.read > end You do not need that loop because sock.read will read until EOF. > > sock.close > response > end > > > > read_from_sock('yahoo.com', 80) returns > > "HTTP/1.1 301 Redirect\r\nDate: Fri, 29 Mar 2013 06:56:20 GMT\r\nConnection: close\r\nServer: YTS/1.20.13\r\nCache-Control: no-store\r\nContent-Type: text/html\r\nContent-Language: en\r\nLocation: http://www.yahoo.com/\r\nContent-Length: 211\r\n\r\nRedirect\n\n\n \"http://www.yahoo.com/\".

\n\n\n\n\u0000" > > read_from_sock('facebook.com', 80) or read_from_sock('google.com', 80) hangs forever > > Where is my mistake? Why don't you use net/http? Cheers robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/