class Palta::Server

Attributes

debug[R]
dir[R]
host[R]
max_threads[R]
msg_recv[R]
port[R]

Public Class Methods

new(options = {}) click to toggle source
# 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

Public Instance Methods

actions(&block) click to toggle source
# File lib/palta/server.rb, line 21
def actions &block
  instance_eval(&block) if block_given?
end
on_any(msg) click to toggle source
# File lib/palta/server.rb, line 31
def on_any msg
  # nothing
end
on_msg(msg) click to toggle source
# File lib/palta/server.rb, line 25
def on_msg msg
  @msg_recv += 1
  on_any(msg)
  send("on_#{msg[:type]}", msg)
end
start() click to toggle source
# 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
stop() click to toggle source
# File lib/palta/server.rb, line 51
def stop
  @threads.each do |t|
    Thread.kill(t)
  end
end