Class: Palta::Server

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Server

Returns a new instance of Server.



11
12
13
14
15
16
17
18
# File 'lib/palta/server.rb', line 11

def initialize options = {}
  @host = options[:host] || "localhost"
  @port = options[:port] || 8888
  @debug = options[:debug] || options[:verbose] || false
  @dir = options[:dir] || "./.palta/data"
  @max_threads = options[:max_threads] || 8
  @threads = []
end

Instance Attribute Details

#debugObject (readonly)

Returns the value of attribute debug.



9
10
11
# File 'lib/palta/server.rb', line 9

def debug
  @debug
end

#dirObject (readonly)

Returns the value of attribute dir.



9
10
11
# File 'lib/palta/server.rb', line 9

def dir
  @dir
end

#hostObject (readonly)

Returns the value of attribute host.



9
10
11
# File 'lib/palta/server.rb', line 9

def host
  @host
end

#max_threadsObject (readonly)

Returns the value of attribute max_threads.



9
10
11
# File 'lib/palta/server.rb', line 9

def max_threads
  @max_threads
end

#portObject (readonly)

Returns the value of attribute port.



9
10
11
# File 'lib/palta/server.rb', line 9

def port
  @port
end

Instance Method Details

#actions(&block) ⇒ Object



20
21
22
# File 'lib/palta/server.rb', line 20

def actions &block
  instance_eval(&block) if block_given?
end

#on_any(msg) ⇒ Object



29
30
31
# File 'lib/palta/server.rb', line 29

def on_any msg
  puts "on_any: #{msg}"
end

#on_msg(msg) ⇒ Object



24
25
26
27
# File 'lib/palta/server.rb', line 24

def on_msg msg
  on_any(msg)
  send("on_#{msg[:type]}", msg)
end

#startObject



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/palta/server.rb', line 33

def start
  @server = TCPServer.new @host, @port
  @max_threads.times do |i|
    @threads << Thread.new do
      loop do
        client = @server.accept
        data = client.recv(1024)
        if @debug
          puts "[Palta::Server] thread #{i} recv: #{data}"
        end
        msg = JSON.parse(data, :symbolize_names => true)
        on_msg(msg)
      end
    end
  end
end

#stopObject



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

def stop
  @threads.each do |t|
    Thread.kill(t)
  end
end