Class: RPC::Clients::Socket

Inherits:
Object
  • Object
show all
Defined in:
lib/rpc/lib/rpc/clients/socket.rb

Instance Method Summary collapse

Constructor Details

#initialize(uri) ⇒ Socket

Returns a new instance of Socket.



9
10
11
12
13
14
# File 'lib/rpc/lib/rpc/clients/socket.rb', line 9

def initialize(uri)
  @uri = URI.parse(uri)

  # Localhost doesn't work for me for some reason.
  @uri.host = "127.0.0.1" if @uri.host.eql?("localhost")
end

Instance Method Details

#async?Boolean

Returns:

  • (Boolean)


45
46
47
# File 'lib/rpc/lib/rpc/clients/socket.rb', line 45

def async?
  false
end

#connectObject



16
17
18
19
20
# File 'lib/rpc/lib/rpc/clients/socket.rb', line 16

def connect
  @client = TCPSocket.new(@uri.host, @uri.port)
rescue Errno::ECONNREFUSED
  raise Errno::ECONNREFUSED.new("You have to start the server first!")
end

#disconnectObject



22
23
24
# File 'lib/rpc/lib/rpc/clients/socket.rb', line 22

def disconnect
  @client.close
end

#run(&block) ⇒ Object



26
27
28
29
30
# File 'lib/rpc/lib/rpc/clients/socket.rb', line 26

def run(&block)
  self.connect
  block.call
  self.disconnect
end

#send(data) ⇒ Object

TODO: support for notifications, probably refactor send to: def send(encoder, data)

binary = encoder.encode(data)
@client.puts(binary)
@client.readline if data[:id]

end … and don’t forget to add support for notifications to the example socket server!



39
40
41
42
43
# File 'lib/rpc/lib/rpc/clients/socket.rb', line 39

def send(data)
  @client.puts(data)
  @client.readline
  # TODO: sync vs. async: @socket.read or a callback and a loop
end