Class: MaxCube::Network::TCP::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/maxcube/network/tcp/client.rb,
lib/maxcube/network/tcp/client/commands.rb

Instance Method Summary collapse

Constructor Details

#initializeClient

Returns a new instance of Client.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/maxcube/network/tcp/client.rb', line 8

def initialize
  @parser = Messages::TCP::Parser.new
  @serializer = Messages::TCP::Serializer.new
  @queue = Queue.new

  @buffer = { recv: { hashes: [], data: [] },
              sent: { hashes: [], data: [] } }
  @history = { recv: { hashes: [], data: [] },
               sent: { hashes: [], data: [] } }

  @hash = nil
  @hash_set = false

  @data_dir = Pathname.new('../data')
  @load_data_dir = @data_dir + 'load'
  @save_data_dir = @data_dir + 'save'

  @verbose = true
  @persist = true
end

Instance Method Details

#closeObject



67
68
69
70
71
72
# File 'lib/maxcube/network/tcp/client.rb', line 67

def close
  STDIN.close
  send_msg('q')
  @socket.close
  @thread.join
end

#connect(host = LOCALHOST, port = PORT) ⇒ Object



29
30
31
32
33
# File 'lib/maxcube/network/tcp/client.rb', line 29

def connect(host = LOCALHOST, port = PORT)
  @socket = TCPSocket.new(host, port)
  @thread = Thread.new(self, &:receiver)
  shell
end

#receiverObject



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/maxcube/network/tcp/client.rb', line 35

def receiver
  puts '<Starting receiver thread ...>'
  while (data = @socket.gets)
    hashes = @parser.parse_tcp_data(data)
    if @verbose
      hashes.each { |h| print_hash(h) }
      puts
    end
    @queue << [data, hashes]
  end
  raise IOError
rescue IOError
  STDIN.close
  puts '<Closing receiver thread ...>'
rescue Messages::InvalidMessage => e
  puts e.to_s.capitalize
end

#shellObject



53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/maxcube/network/tcp/client.rb', line 53

def shell
  puts "Welcome to interactive shell!\n" \
       "Type 'help' for list of commands.\n\n"
  STDIN.each do |line|
    refresh_buffer
    command(line)
    puts
  end
  raise Interrupt
rescue IOError, Interrupt
  puts "\nClosing shell ..."
  close
end