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, oj_options: nil) ⇒ Client

Returns a new instance of Client.



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

def initialize(host: "127.0.0.1", port: 1234, delimeter: "#", unix_socket: nil, oj_options: nil)
  Oj.default_options = oj_options if oj_options
  @delimeter = delimeter
  @unix_socket = unix_socket
  @host = host
  @port = port
end

Instance Method Details

#handle_send_receive(socket, message) ⇒ Object



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

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))
ensure
  socket.close
end

#send(message) ⇒ Object



106
107
108
109
110
111
112
# File 'lib/json-socket.rb', line 106

def send(message)
  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
end