1 # -*- encoding: binary -*-
4 class MogileFS::Socket < Kgio::Socket
5 def self.start(host, port)
6 sock = super(Socket.sockaddr_in(port, host))
7 Socket.const_defined?(:TCP_NODELAY) and
8 sock.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
12 def self.tcp(host, port, timeout = 5)
13 sock = start(host, port)
14 unless sock.kgio_wait_writable(timeout)
16 raise MogileFS::Timeout, 'socket connect timeout'
21 def timed_read(len, dst = "", timeout = 5)
22 case rc = kgio_tryread(len, dst)
24 kgio_wait_readable(timeout) or raise MogileFS::Timeout, "read timeout"
30 def timed_peek(len, dst, timeout = 5)
31 case rc = kgio_trypeek(len, dst)
33 kgio_wait_readable(timeout) or raise MogileFS::Timeout, "peek timeout"
39 def timed_write(buffer, timeout = 5)
40 case rc = kgio_trywrite(buffer)
42 kgio_wait_writable(timeout) or raise MogileFS::Timeout, "write timeout"
50 SEP_RE = /\A(.*?#{Regexp.escape("\n")})/
51 def timed_gets(timeout = 5)
52 unless defined?(@rbuf)
53 @rbuf = timed_read(1024, "", timeout) or return # EOF
56 @rbuf.sub!(SEP_RE, "") and return $1
58 if timed_read(1024, tmp, timeout)
61 # EOF, return the last buffered bit even without SEP_RE matching
62 # (not ideal for MogileFS, this is an error)
63 return @rbuf.empty? ? nil : @rbuf.slice!(0, @rbuf.size)