Class: MonoTalk::Server

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

Instance Method Summary collapse

Constructor Details

#initialize(servicename, routine) ⇒ Server

Returns a new instance of Server.



8
9
10
11
12
13
14
15
16
17
# File 'lib/module/server.rb', line 8

def initialize(servicename,routine)
  @io = STDERR
  @servicename = servicename.to_sym
  @routine = routine

  @io.puts Color.cyan "Command List"
  @routine.each do |key,value|
    @io.puts "#{key} -> #{value}"
  end
end

Instance Method Details

#acceptObject



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/module/server.rb', line 19

def accept
  @server = TCPServer.open(Mono::PORT[@servicename])
  @io.puts 'Acception start, waiting for data...'
  @sock = @server.accept
  @server.close
  begin
    hash = JSON.parse @sock.gets
    @io.puts hash
    @sock.write routing(hash)
  rescue => e
    @io.puts Color.red 'GIVE UP! SOMETHING BAD HAPPEN!'
    @io.puts Color.yellow hash
    @io.puts Color.magenta e 
  ensure
    @sock.close
    @io.puts 'Socket was closed.'
  end
end

#closeObject



55
56
57
58
# File 'lib/module/server.rb', line 55

def close
  @server.close
  @io.puts 'Server closed.'
end

#routing(hash) ⇒ Object



50
51
52
53
# File 'lib/module/server.rb', line 50

def routing(hash)
  return "Undefined command, ABORT -> #{hash['command']}" unless @routine[hash['command']]
  return @routine[hash['command']].call(hash['params'])
end

#test(hash) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
# File 'lib/module/server.rb', line 38

def test(hash)
  @io.puts Color.yellow "Starting test..."
  @server = TCPServer.open(Mono::PORT[@servicename])
  STDERR.puts 'Acception start, waiting for data...'
  @server.close
  @io.puts hash
  ret = routing(hash)
  @io.puts ret
  @io.puts 'Test was closed.'
  return ret
end