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