Class: AsyncTCPSocket
- Inherits:
-
AsyncEmitter
- Object
- AsyncEmitter
- AsyncTCPSocket
- Defined in:
- lib/async_tcpsocket.rb
Overview
An asyncronous TCP socket implementation (wraps TCPSocket)
Inherits AsyncEmitter and emits three events, :data, :close and :error. :data is emitted when data is recieved, :close is emitted if the other side closes the connection and it is detected, :error emits errors
Example
require 'async_tcpsocket'
socket = AsyncTCPSocket.new
socket.once :error, Proc.new { |err|
STDERR.puts "Error: #{err}"
socket.close
}
socket.once :close, Proc.new { |err|
socket.close
}
socket.on :data, Proc.new { |data|
puts "#{data}"
}
socket.connect 'localhost', 80
socket.puts "GET / HTTP 1.1\r\n\r\n"
#wait for return key
gets
socket.close
Instance Method Summary collapse
-
#close ⇒ Object
closes the connection.
-
#connect(host, port) ⇒ Object
connect to a server - if the socket is already connected it will be closed.
-
#initialize(socket = nil) ⇒ AsyncTCPSocket
constructor
constructor.
-
#puts(data) ⇒ Object
sends data asyncronously - non-string objects will need to be serialized.
Constructor Details
#initialize(socket = nil) ⇒ AsyncTCPSocket
constructor
49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/async_tcpsocket.rb', line 49 def initialize (socket=nil) super() @socket = socket @write_data = nil @write_semaphore = Mutex.new @write_cv = ConditionVariable.new if socket != nil threads end end |
Instance Method Details
#close ⇒ Object
closes the connection
83 84 85 86 87 88 89 90 |
# File 'lib/async_tcpsocket.rb', line 83 def close if @socket != nil @socket.close Thread.kill @read_thread Thread.kill @write_thread @socket = nil end end |
#connect(host, port) ⇒ Object
connect to a server - if the socket is already connected it will be closed
68 69 70 71 72 73 74 75 76 77 78 |
# File 'lib/async_tcpsocket.rb', line 68 def connect (host, port) close begin @socket = TCPSocket.new host, port rescue Exception => e emit :error, e end threads end |
#puts(data) ⇒ Object
sends data asyncronously - non-string objects will need to be serialized
#############################################################
98 99 100 101 102 103 |
# File 'lib/async_tcpsocket.rb', line 98 def puts data @write_semaphore.synchronize do @write_data = data @write_cv.signal end end |