Class: TCPMessenger::Messenger
- Inherits:
-
Object
- Object
- TCPMessenger::Messenger
- Defined in:
- lib/tcp_messenger/messenger.rb
Instance Method Summary collapse
- #close ⇒ Object
- #closed? ⇒ Boolean
-
#initialize(socket, duck_types:, max_message_length:) ⇒ Messenger
constructor
A new instance of Messenger.
- #receive ⇒ Object
- #send(message) ⇒ Object
Constructor Details
#initialize(socket, duck_types:, max_message_length:) ⇒ Messenger
Returns a new instance of Messenger.
4 5 6 7 8 9 10 11 |
# File 'lib/tcp_messenger/messenger.rb', line 4 def initialize(socket, duck_types: , max_message_length: ) @socket = socket @max_message_length = @close_mutex = QuackConcurrency::ReentrantMutex.new @send_mutex = Mutex.new @receive_mutex = Mutex.new @closed = false end |
Instance Method Details
#close ⇒ Object
13 14 15 16 17 18 19 20 21 22 23 24 25 |
# File 'lib/tcp_messenger/messenger.rb', line 13 def close @close_mutex.synchronize do raise ClosedError if closed? begin @socket.close rescue raise ConnectionError ensure @closed = true end end nil end |
#closed? ⇒ Boolean
27 28 29 |
# File 'lib/tcp_messenger/messenger.rb', line 27 def closed? @closed end |
#receive ⇒ Object
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/tcp_messenger/messenger.rb', line 51 def receive @receive_mutex.synchronize do = '' loop do char = receive_byte break if char == "\n" binding.pry if char == nil << char if .length > @max_message_length @close_mutex.synchronize { close unless closed? } loop do char = receive_byte break if char == "\n" end raise MessageTooLong end end = .gsub('\n', "\n") return end end |
#send(message) ⇒ Object
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/tcp_messenger/messenger.rb', line 31 def send() @send_mutex.synchronize do raise ClosedError if closed? raise "'message' must be a string." unless .respond_to?(:to_s) = .to_s = .gsub("\n", '\n') raise MessageTooLong if .length > @max_message_length begin @socket.puts() rescue @close_mutex.synchronize do raise ClosedError if closed? close raise ConnectionError end end end nil end |