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
19
# 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 = []
  @msg_recv = 0
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

#msg_recvObject (readonly)

Returns the value of attribute msg_recv.



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

def msg_recv
  @msg_recv
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



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

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

#on_any(msg) ⇒ Object



31
32
33
# File 'lib/palta/server.rb', line 31

def on_any msg
  # nothing
end

#on_msg(msg) ⇒ Object



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

def on_msg msg
  @msg_recv += 1
  on_any(msg)
  send("on_#{msg[:type]}", msg)
end

#startObject



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

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)
        client.close
        puts "[Palta::Server] thread #{i} recv: #{data}" if @debug
        msg = JSON.parse(data, :symbolize_names => true)
        on_msg(msg)
      end
    end
  end
end

#stopObject



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

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