http_file: remove unused attrs
[ruby-mogilefs-client.git] / lib / mogilefs / socket / pure_ruby.rb
blobb820b2063537f4bd572461e6711c1ad4de5f28a5
1 # -*- encoding: binary -*-
2 # internal implementation details here, do not rely on them in your code
4 class MogileFS::Socket < Socket
5   include MogileFS::SocketCommon
7   def self.start(host, port)
8     sock = new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
9     begin
10       sock.connect_nonblock(sockaddr_in(port, host))
11     rescue Errno::EINPROGRESS
12     end
13     sock.post_init(host, port)
14   end
16   def self.tcp(host, port, timeout = 5)
17     sock = start(host, port)
18     unless IO.select(nil, [ sock ], nil, timeout)
19       sock.close
20       raise MogileFS::Timeout, 'socket connect timeout'
21     end
22     sock
23   end
25   def timed_read(len, dst = "", timeout = 5)
26     begin
27       IO.select([self], nil, nil, timeout) or unreadable_socket!
28       return read_nonblock(len, dst)
29     rescue Errno::EAGAIN
30     rescue EOFError
31       return
32     end while true
33   end
35   def timed_peek(len, dst, timeout = 5)
36     begin
37       IO.select([self], nil, nil, timeout) or unreadable_socket!
38       rc = recv_nonblock(len, Socket::MSG_PEEK)
39       return rc.empty? ? nil : dst.replace(rc)
40     rescue Errno::EAGAIN
41     rescue EOFError
42       dst.replace("")
43       return
44     end while true
45   end
47   def timed_write(buf, timeout = 5)
48     written = 0
49     expect = buf.bytesize
50     begin
51       rc = write_nonblock(buf)
52       return expect if rc == buf.bytesize
53       written += rc
55       if buf.respond_to?(:byteslice)
56         buf = buf.byteslice(rc, buf.bytesize)
57       else
58         if buf.respond_to?(:encoding) && buf.encoding != Encoding::BINARY
59           buf = buf.dup.force_encoding(Encoding::BINARY)
60         end
61         buf = buf.slice(rc, buf.bytesize)
62       end
63     rescue Errno::EAGAIN
64       IO.select(nil, [self], nil, timeout) or
65         request_truncated!(written, expect)
66     end while true
67   end
68 end