Class: DemoSocket

Inherits:
Object
  • Object
show all
Defined in:
lib/demo_socket.rb

Defined Under Namespace

Classes: BadMessage, DeadSocket, SocketError

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(socket) ⇒ DemoSocket

Returns a new instance of DemoSocket.



6
7
8
9
10
# File 'lib/demo_socket.rb', line 6

def initialize(socket)
  @tcp_socket = socket
  @hostname = @tcp_socket.peeraddr[2]
  @addr = @tcp_socket.peeraddr[3]
end

Instance Attribute Details

#addrObject (readonly)

Returns the value of attribute addr.



12
13
14
# File 'lib/demo_socket.rb', line 12

def addr
  @addr
end

#hostnameObject (readonly)

Returns the value of attribute hostname.



12
13
14
# File 'lib/demo_socket.rb', line 12

def hostname
  @hostname
end

Class Method Details

.connect(addr, port) ⇒ Object



14
15
16
# File 'lib/demo_socket.rb', line 14

def self.connect(addr, port)
  new TCPSocket.new(addr, port)
end

Instance Method Details

#closeObject



18
19
20
# File 'lib/demo_socket.rb', line 18

def close
  @tcp_socket.close
end

#recvObject



37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/demo_socket.rb', line 37

def recv
  header = @tcp_socket.recv(4)
  raise BadMessage if header.size < 4

  expected_length = header.unpack('N')[0]
  msg = @tcp_socket.recv(expected_length)
  raise BadMessage if msg.size < expected_length

  puts ">>> #{msg.inspect}" if ENV['DEMO_DEBUG']
  
  JSON.parse(msg)
rescue Errno::ECONNRESET
  raise DeadSocket
end

#send(data) ⇒ Object



22
23
24
25
26
27
28
29
30
31
# File 'lib/demo_socket.rb', line 22

def send(data)
  msg = data.to_json
  begin
    puts "<<< #{msg.inspect}" if ENV['DEMO_DEBUG']
    @tcp_socket.send([msg.size].pack('N'), 0)
    @tcp_socket.send(msg, 0)
  rescue Errno::ECONNRESET, Errno::EPIPE => e
    raise DeadSocket
  end
end