Class: AsyncTCPSocket

Inherits:
AsyncEmitter
  • Object
show all
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

Author:

  • Greg Martin

Instance Method Summary collapse

Constructor Details

#initialize(socket = nil) ⇒ AsyncTCPSocket

constructor

Parameters:

  • socket (TCPSocket) (defaults to: nil)

    or nil


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

#closeObject

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

Parameters:

  • host (String)

    the server host address

  • port (FixedNum)

    the server port


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

#############################################################

Parameters:

  • data (Object)
    • the data to send


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