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.



85
86
87
88
89
90
91
# File 'lib/json-socket.rb', line 85

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



93
94
95
96
97
98
99
# File 'lib/json-socket.rb', line 93

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



101
102
103
104
105
106
107
108
109
110
111
# File 'lib/json-socket.rb', line 101

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