Class: Empp::TcpConnection
- Inherits:
-
Object
- Object
- Empp::TcpConnection
- Defined in:
- lib/empp/tcp_connection.rb
Class Method Summary collapse
Instance Method Summary collapse
- #alive? ⇒ Boolean
- #close ⇒ Object
- #connect ⇒ Object
-
#initialize(host, port) ⇒ TcpConnection
constructor
A new instance of TcpConnection.
- #receive(count = 0) ⇒ Object
- #send(data) ⇒ Object
Constructor Details
#initialize(host, port) ⇒ TcpConnection
Returns a new instance of TcpConnection.
8 9 10 11 12 13 14 15 |
# File 'lib/empp/tcp_connection.rb', line 8 def initialize(host, port) @socket = nil @host = host @port = port @max_to_read = 4096 @logger = EmppLogger.instance @alive = false end |
Class Method Details
.getConnection(host, port) ⇒ Object
17 18 19 |
# File 'lib/empp/tcp_connection.rb', line 17 def self.getConnection(host, port) return self.new(host, port) end |
Instance Method Details
#alive? ⇒ Boolean
21 22 23 |
# File 'lib/empp/tcp_connection.rb', line 21 def alive? @alive end |
#close ⇒ Object
56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
# File 'lib/empp/tcp_connection.rb', line 56 def close @logger.debug("Enter TcpConnection::close") begin @alive = false if @socket @socket.close() end rescue @logger.warn("Unable to close socket.") end @logger.debug("Leave TcpConnection::close") end |
#connect ⇒ Object
41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/empp/tcp_connection.rb', line 41 def connect @logger.debug("Enter TcpConnection::connect") begin @socket = TCPSocket.new(@host, @port) @alive = true rescue @alive = false @socket = nil @logger.fatal("Open socket error for host=#{@host}, port=#{@port}") end @logger.debug("Leave TcpConnection::connect") end |
#receive(count = 0) ⇒ Object
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
# File 'lib/empp/tcp_connection.rb', line 71 def receive(count = 0) @logger.debug("Enter TcpConnection::receive") count ||= @max_to_read if count < 0 || count > @max_to_read return end bytes = nil begin while !bytes || bytes.length == 0 if @socket bytes = @socket.recvfrom(count)[0] else raise end end rescue @logger.fatal("TcpConnection::receive: get exception from socket recvFrom") @alive = false return end @logger.info("TcpConnectin receive bytes=" + bytes.unpack("H*").to_s ) @logger.debug("Leave TcpConnection::receive") return bytes end |
#send(data) ⇒ Object
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/empp/tcp_connection.rb', line 25 def send(data) @logger.debug("Enter TcpConnection::send") @logger.debug("TcpConnection: send bytes:#{data.unpack("H*")}") if @socket begin @socket.write(data) rescue @logger.fatal("Get exception to write data") @alive = false end end @logger.debug("Leave TcpConnection::send") end |