Class: Warchat::Network::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/warchat/network/connection.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeConnection

Returns a new instance of Connection.



11
12
13
14
15
# File 'lib/warchat/network/connection.rb', line 11

def initialize
  @closed = true
  @queue = []
  @mutex = Mutex.new
end

Instance Attribute Details

#on_closeObject

Returns the value of attribute on_close.



9
10
11
# File 'lib/warchat/network/connection.rb', line 9

def on_close
  @on_close
end

#on_receiveObject

Returns the value of attribute on_receive.



9
10
11
# File 'lib/warchat/network/connection.rb', line 9

def on_receive
  @on_receive
end

#on_sendObject

Returns the value of attribute on_send.



9
10
11
# File 'lib/warchat/network/connection.rb', line 9

def on_send
  @on_send
end

Instance Method Details

#close(reason = "") ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
# File 'lib/warchat/network/connection.rb', line 29

def close reason = ""
  return if is_closed?

  on_close and on_close.call(reason)
  
  @mutex.synchronize do 
    @closed = true
    @socket.close
  end     
  ([@request_thread,@response_thread]-[Thread.current]).each &:join
end

#handle_requestsObject



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/warchat/network/connection.rb', line 62

def handle_requests
  until is_closed?
    @mutex.synchronize do
      until @queue.empty?
        request = @queue.shift
        unless is_closed?
          request.stream @socket
          @socket.flush
          on_send and on_send.call(request) 
        end
      end
    end
    sleep 0.01
  end
rescue Exception => e
  Warchat.debug e.message
  Warchat.debug e.backtrace
end

#handle_responsesObject



51
52
53
54
55
56
57
58
59
60
# File 'lib/warchat/network/connection.rb', line 51

def handle_responses
  until is_closed?
    response = Response.new(@socket)
    on_receive and on_receive.call(response) unless is_closed?
    sleep 0.01
  end
rescue Exception => e
  Warchat.debug e.message
  Warchat.debug e.backtrace unless e.is_a? IOError
end

#is_closed?Boolean

Returns:

  • (Boolean)


41
42
43
# File 'lib/warchat/network/connection.rb', line 41

def is_closed? 
  @closed or @socket.nil?
end

#send_request(request) ⇒ Object



45
46
47
48
49
# File 'lib/warchat/network/connection.rb', line 45

def send_request request
  @mutex.synchronize do
    @queue << request
  end
end

#start(host = "m.us.wowarmory.com", port = 8780) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
# File 'lib/warchat/network/connection.rb', line 17

def start host="m.us.wowarmory.com",port=8780
  close

  @closed = false;
  @socket = TCPSocket.open(host,port)
  @socket.sync = false
  @request_thread = Thread.new &method(:handle_requests)
  @response_thread = Thread.new &method(:handle_responses)
  @request_thread['name'] = 'Request Thead'
  @response_thread['name'] = 'Response Thread'
end