Class: UDPRest::Client

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host, port) ⇒ Client

Returns a new instance of Client.



99
100
101
102
103
104
105
106
# File 'lib/udp_rest.rb', line 99

def initialize(host, port)
  @max_packet_size = 512

  self.host = host
  self.port = port
  self.socket = UDPSocket.new
  self.timeout = 5.0
end

Instance Attribute Details

#hostObject

Returns the value of attribute host.



94
95
96
# File 'lib/udp_rest.rb', line 94

def host
  @host
end

#portObject

Returns the value of attribute port.



95
96
97
# File 'lib/udp_rest.rb', line 95

def port
  @port
end

#socketObject

Returns the value of attribute socket.



96
97
98
# File 'lib/udp_rest.rb', line 96

def socket
  @socket
end

#timeoutObject

Returns the value of attribute timeout.



97
98
99
# File 'lib/udp_rest.rb', line 97

def timeout
  @timeout
end

Class Method Details

.get(url) ⇒ Object



134
135
136
# File 'lib/udp_rest.rb', line 134

def self.get(url)
  self.uhttp('GET', url)
end

.uhttp(req_method, url) ⇒ Object



121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/udp_rest.rb', line 121

def self.uhttp(req_method, url)
  uri = URI(url)
  client = self.new(uri.host, uri.port || 80)
  
  req = UHTTPRequest.new
  req.req_method = req_method
  req.path = uri.path
  req.query = uri.query

  packet = client.send_text(req.to_s)
  UHTTPResponse.parse(packet.text)
end

Instance Method Details

#send_text(text) ⇒ Object



108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/udp_rest.rb', line 108

def send_text(text)
  thread = WorkerThread.new.start :timeout => self.timeout do
    self.socket.send(text, 0, self.host, self.port)
    response_data = self.socket.recvfrom(@max_packet_size)
    UDPPacket.new(response_data)
  end

  thread.join
  packet = thread.value
  raise "Request Timeout (#{host}:#{port})" if packet.nil?
  return packet
end