Class: JSONSocket::Client

Inherits:
Object
  • Object
show all
Includes:
JsonEncodeDecode
Defined in:
lib/json-socket.rb

Instance Method Summary collapse

Methods included from JsonEncodeDecode

#encode_json, #parse_json

Constructor Details

#initialize(host: "127.0.0.1", port: 1234, delimeter: "#", unix_socket: nil) ⇒ Client

Returns a new instance of Client.



82
83
84
85
86
87
# File 'lib/json-socket.rb', line 82

def initialize(host: "127.0.0.1", port: 1234, delimeter: "#", unix_socket: nil)
  @delimeter = delimeter
  @unix_socket = unix_socket
  @host = host
  @port = port
end

Instance Method Details

#handle_send_receive(socket, message) ⇒ Object



89
90
91
92
93
94
95
# File 'lib/json-socket.rb', line 89

def handle_send_receive(socket, message)
  socket.set_encoding 'UTF-8'
  strigified = encode_json(message)
  socket << "#{strigified.bytesize}#{@delimeter}#{strigified}"
  message_length = socket.gets(@delimeter).to_i
  return parse_json(socket.read(message_length))
end

#send(message) ⇒ Object



97
98
99
100
101
102
103
104
105
106
107
# File 'lib/json-socket.rb', line 97

def send(message)
  begin
    if @unix_socket
      UNIXSocket.open(@unix_socket) {| socket| handle_send_receive(socket, message) }
    else
      TCPSocket.open(@host, @port) {| socket| handle_send_receive(socket, message) }
    end
  rescue Exception => e
    STDERR.puts e
  end
end