Class: NetworkFacade::Base::Server

Inherits:
Object
  • Object
show all
Defined in:
lib/network-facade/base.rb

Direct Known Subclasses

TCP::Server, Unix::Server

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Server

Returns a new instance of Server.



103
104
105
106
107
108
109
110
# File 'lib/network-facade/base.rb', line 103

def initialize(options = {})
  @options = options
  require 'zlib' if @options[:compress]
  @options[:mode] ||= :select
  @clients = (@options[:mode] == :select ? [@options[:server]] : [])
  @objs = {}
  @thread = nil
end

Instance Attribute Details

#threadObject (readonly)

Returns the value of attribute thread.



101
102
103
# File 'lib/network-facade/base.rb', line 101

def thread
  @thread
end

Instance Method Details

#add(obj) ⇒ Object Also known as: <<



116
117
118
119
120
121
# File 'lib/network-facade/base.rb', line 116

def add(obj)
  id = obj.class.name.downcase
  NetworkFacade.log(:info, "Adding new object #{obj.inspect} at /#{id}")
  @objs[id] = obj
  self
end

#client_id(client) ⇒ Object



112
113
114
# File 'lib/network-facade/base.rb', line 112

def client_id(client)
  "0x%08x" % client.object_id
end

#startObject



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/network-facade/base.rb', line 124

def start
  if @options[:mode] == :select
    loop do
      readable, writable, errors, timeout = IO.select(@clients)
      begin
        if readable.include?(@options[:server])
          @clients << accept
          readable.delete(@options[:server])
        end
      rescue Exception
        NetworkFacade.log(:warn, "An error occured when accapting new client")
        NetworkFacade.log(:warn, $!)
        next
      end

      readable.each do |client|
        process(client)
      end
    end
  elsif @options[:mode] == :thread
    @thread = Thread.new do
      loop do
        GC.start
        Thread.new(accept) do |client|
          process(client)
        end
      end
    end
  else
    raise "Unknown mode #{@options[:mode]}"
  end
end