Class: Client

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

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(demo_socket) ⇒ Client

Returns a new instance of Client.



26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/client.rb', line 26

def initialize(demo_socket)
  @socket = demo_socket

  Client.add self

  @lock = Mutex.new

  @outbox = Queue.new
  @inbox = Queue.new

  @comm_thread = start_comm
  @pulse_thread = start_heartbeat
end

Class Attribute Details

.client_indexObject

Returns the value of attribute client_index.



7
8
9
# File 'lib/client.rb', line 7

def client_index
  @client_index
end

.clientsObject

Returns the value of attribute clients.



7
8
9
# File 'lib/client.rb', line 7

def clients
  @clients
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



24
25
26
# File 'lib/client.rb', line 24

def name
  @name
end

Class Method Details

.add(client) ⇒ Object



15
16
17
18
# File 'lib/client.rb', line 15

def add(client)
  clients << client
  client_index[client.addr] = client
end

.remove(client) ⇒ Object



9
10
11
12
13
# File 'lib/client.rb', line 9

def remove(client)
  puts "--- #{client.addr} has disconnected"
  clients.delete client
  client_index.delete client.addr
end

Instance Method Details

#addrObject



64
65
66
# File 'lib/client.rb', line 64

def addr
  @socket.addr
end

#hostnameObject



68
69
70
# File 'lib/client.rb', line 68

def hostname
  @socket.hostname
end

#lock(&block) ⇒ Object



40
41
42
# File 'lib/client.rb', line 40

def lock(&block)
  @lock.synchronize &block
end

#msg(data) ⇒ Object



57
58
59
60
61
62
# File 'lib/client.rb', line 57

def msg(data)
  lock {
    send data
    recv
  }
end

#recvObject



48
49
50
51
52
53
54
55
# File 'lib/client.rb', line 48

def recv
  SystemTimer.timeout 1 do
    @inbox.pop
  end
rescue Timeout::Error
  puts "#{addr} timed out"
  false
end

#send(data) ⇒ Object



44
45
46
# File 'lib/client.rb', line 44

def send(data)
  @outbox << data
end

#start_commObject



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/client.rb', line 72

def start_comm
  Thread.new {
    loop do
      msg = @outbox.pop
      begin
        @socket.send msg
        @inbox << @socket.recv
      rescue DemoSocket::SocketError => e
        Client.remove(self)
        @pulse_thread.kill
        @comm_thread.kill
      end
    end
  }
end

#start_heartbeatObject



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/client.rb', line 88

def start_heartbeat
  client = self
  Thread.new {
    loop do
      response = msg('t' => 'HRT')
      if response
        @name = response['name']
      else
        Client.remove(self)
        @comm_thread.kill
        @pulse_thread.kill
      end
      sleep 2
    end
  }
end