Class: Fargo::Server

Inherits:
Object
  • Object
show all
Includes:
Publisher
Defined in:
lib/fargo/server.rb

Instance Attribute Summary

Attributes included from Publisher

#subscribers

Instance Method Summary collapse

Methods included from Publisher

#publish, #subscribe, #subscribed_to?, #unsubscribe

Constructor Details

#initialize(options = {}) ⇒ Server

Returns a new instance of Server.



6
7
8
9
10
# File 'lib/fargo/server.rb', line 6

def initialize options = {}
  @options = options
  @options[:address] = '0.0.0.0'
  @peers = []
end

Instance Method Details

#connectObject



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

def connect
  return if connected?
  
  Fargo.logger.info "#{self}: Starting server on #{@options[:address]}:#{@options[:port]}"

  @server = TCPServer.new @options[:address], @options[:port]

  @active_thread = Thread.start { loop {
    
    connection = @options[:connection].new @options.merge(:first => false)
    
    connection_type = self.class.name.split("::").last.downcase
    disconnect_symbol = :"#{connection_type}_disconnected"
    
    connection.subscribe{ |type, hash|
      @peers.delete connection if type == disconnect_symbol
    }
    
    connection.socket = @server.accept
    connection.listen
    @peers << connection
  } }
end

#connected?Boolean

Returns:

  • (Boolean)


12
13
14
# File 'lib/fargo/server.rb', line 12

def connected?
  !@server.nil?
end

#disconnectObject



40
41
42
43
44
45
46
47
48
49
# File 'lib/fargo/server.rb', line 40

def disconnect
  Fargo.logger.info "#{self}: disconnecting..."
  @active_thread.exit if @active_thread
  
  @server.close if @server rescue nil
  @server = nil
  
  @peers.each{ |p| p.disconnect } 
  @peers.clear
end