Class: EventSocket

Inherits:
Object show all
Defined in:
lib/adhearsion/foundation/event_socket.rb

Defined Under Namespace

Classes: ConnectionError

Constant Summary collapse

MAX_CHUNK_SIZE =
256 * 1024

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host, port, handler = nil, &block) ⇒ EventSocket

Returns a new instance of EventSocket.

Raises:

  • (ArgumentError)


71
72
73
74
75
76
77
78
79
80
81
# File 'lib/adhearsion/foundation/event_socket.rb', line 71

def initialize(host, port, handler=nil, &block)
  raise ArgumentError, "Cannot supply both a handler object and a block" if handler && block_given?
  raise ArgumentError, "Must supply either a handler object or a block" if !handler && !block_given?
  
  @state_lock = Mutex.new
  @host  = host
  @port  = port
  
  @state = :new
  @handler = handler || new_handler_from_block(&block)
end

Class Method Details

.connect(*args, &block) ⇒ Object

Creates and returns a connected EventSocket instance.



62
63
64
65
66
# File 'lib/adhearsion/foundation/event_socket.rb', line 62

def connect(*args, &block)
  instance = new(*args, &block)
  instance.connect!
  instance
end

Instance Method Details

#connect!Object



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/adhearsion/foundation/event_socket.rb', line 87

def connect!
  @state_lock.synchronize do
    if @state.equal? :connected
      raise ConnectionError, "Already connected!"
    else
      @socket = TCPSocket.new(@host, @port)
      @state  = :connected
    end
  end
  @handler.connected rescue nil
  @reader_thread = spawn_reader_thread
  self
rescue => error
  @state = :failed
  raise error
end

#disconnect!Object

Disconnects this EventSocket and sets the state to :stopped



118
119
120
121
122
123
# File 'lib/adhearsion/foundation/event_socket.rb', line 118

def disconnect!
  @state_lock.synchronize do
    @socket.close rescue nil
    @state = :stopped
  end
end

#joinObject

Joins the Thread which reads data off the socket.



128
129
130
131
132
133
134
135
136
# File 'lib/adhearsion/foundation/event_socket.rb', line 128

def join
  @state_lock.synchronize do
    if @state.equal? :connected
      @reader_thread.join
    else
      nil
    end
  end
end

#receive_data(data) ⇒ Object



138
139
140
# File 'lib/adhearsion/foundation/event_socket.rb', line 138

def receive_data(data)
  @handler.receive_data(data)
end

#send_data(data) ⇒ Object

Thread-safe implementation of write.

Parameters:

  • data (String)

    Data to write



109
110
111
112
113
114
# File 'lib/adhearsion/foundation/event_socket.rb', line 109

def send_data(data)
  # Note: TCPSocket#write is intrinsically Thread-safe
  @socket.write data
rescue
  connection_dropped!
end

#stateObject



83
84
85
# File 'lib/adhearsion/foundation/event_socket.rb', line 83

def state
  @state_lock.synchronize { @state }
end