Class: SmartFox::Socket::Connection
- Inherits:
-
Object
- Object
- SmartFox::Socket::Connection
- Defined in:
- lib/smartfox/socket/connection.rb
Constant Summary collapse
- DEFAULT_PORT =
9339
Instance Attribute Summary collapse
-
#connected ⇒ Object
(also: #connected?)
readonly
Returns the value of attribute connected.
Instance Method Summary collapse
- #connect ⇒ Object
- #disconnect ⇒ Object
- #event_loop ⇒ Object
-
#initialize(client) ⇒ Connection
constructor
A new instance of Connection.
- #inspect ⇒ Object
- #send_data(data) ⇒ Object
Constructor Details
#initialize(client) ⇒ Connection
Returns a new instance of Connection.
8 9 10 11 12 13 14 15 |
# File 'lib/smartfox/socket/connection.rb', line 8 def initialize(client) @client = client @connected = false @event_thread = nil @disconnecting = false @buffer = String.new @packets = [] end |
Instance Attribute Details
#connected ⇒ Object (readonly) Also known as: connected?
Returns the value of attribute connected.
5 6 7 |
# File 'lib/smartfox/socket/connection.rb', line 5 def connected @connected end |
Instance Method Details
#connect ⇒ Object
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/smartfox/socket/connection.rb', line 17 def connect begin SmartFox::Logger.info "SmartFox::Socket::Connection#connect began" @socket = TCPSocket.new(@client.server, @client.port || DEFAULT_PORT) # SmartFox sockets will send a cross domain policy, receive this packet # before we do anything else or the connection will hang @socket.readpartial(4096) @connected = true @event_thread = Thread.start(self) { |connection| connection.event_loop } @client.connect_succeeded rescue => e SmartFox::Logger.error "In SmartFox::Socket::Connection#connect:" SmartFox::Logger.exception e raise e end end |
#disconnect ⇒ Object
35 36 37 38 39 40 41 42 |
# File 'lib/smartfox/socket/connection.rb', line 35 def disconnect @disconnecting = true @socket.close if @socket while @connected Thread.pass end end |
#event_loop ⇒ Object
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
# File 'lib/smartfox/socket/connection.rb', line 48 def event_loop SmartFox::Logger.info "SmartFox::Socket::Connection#event_loop began" ticks = 0 until @disconnecting SmartFox::Logger.debug "SmartFox::Socket::Connection#event_loop tick #{ticks}" buffer = String.new begin buffer = @socket.readpartial(4096) @buffer += buffer if buffer while index = @buffer.index("\0") @packets << @buffer.slice!(0..index) end @packets.each { |packet| @client.packet_recieved(packet) } @packets.clear rescue => e Thread.pass end ticks += 1 end @connected = false end |
#inspect ⇒ Object
76 77 78 |
# File 'lib/smartfox/socket/connection.rb', line 76 def inspect "#<#{self.class.name}:#{object_id} server:#{@client.server} port:#{@client.port || DEFAULT_PORT}>" end |
#send_data(data) ⇒ Object
44 45 46 |
# File 'lib/smartfox/socket/connection.rb', line 44 def send_data(data) @socket.write(data) end |