Class: TCPMessenger::Messenger

Inherits:
Object
  • Object
show all
Defined in:
lib/tcp_messenger/messenger.rb

Instance Method Summary collapse

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 = max_message_length
  @close_mutex = QuackConcurrency::ReentrantMutex.new
  @send_mutex = Mutex.new
  @receive_mutex = Mutex.new
  @closed = false
end

Instance Method Details

#closeObject



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

Returns:

  • (Boolean)


27
28
29
# File 'lib/tcp_messenger/messenger.rb', line 27

def closed?
  @closed
end

#receiveObject



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
    encoded_message = ''
    loop do
      char = receive_byte
      break if char == "\n"
      binding.pry if char == nil
      encoded_message << char
      if encoded_message.length > @max_message_length
        @close_mutex.synchronize { close unless closed? }
        loop do
          char = receive_byte
          break if char == "\n"
        end
        raise MessageTooLong
      end
    end
    message = encoded_message.gsub('\n', "\n")
    return message
  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(message)
  @send_mutex.synchronize do
    raise ClosedError if closed?
    raise "'message' must be a string." unless message.respond_to?(:to_s)
    message = message.to_s
    encoded_message = message.gsub("\n", '\n')
    raise MessageTooLong if encoded_message.length > @max_message_length
    begin
      @socket.puts(encoded_message)
    rescue
      @close_mutex.synchronize do
        raise ClosedError if closed?
        close
        raise ConnectionError
      end
    end
  end
  nil
end