Class: UDPAgent
- Inherits:
-
Object
- Object
- UDPAgent
- Defined in:
- lib/minitcp.rb
Class Method Summary collapse
-
.on_datagramme(host, port) ⇒ Object
recieved UDP datagramme, bloc can ellaborate a reply, which will be sending to client.
-
.on_timer(periode, options) ⇒ Object
send datagram on timer.
-
.send_datagram(host, port, mess) ⇒ Object
maintain a connection to a UDP serveur, sleep timer_interconnection_ms millisecondes beetwen each reconnections.
- .send_datagram_on_socket(socket, host, port, mess) ⇒ Object
Class Method Details
.on_datagramme(host, port) ⇒ Object
recieved UDP datagramme, bloc can ellaborate a reply, which will be sending to client
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 |
# File 'lib/minitcp.rb', line 309 def self.on_datagramme(host,port) serv = UDPSocket.new serv.bind(host, port) Thread.new do loop do begin Thread.new(*serv.recvfrom(1024)) do |data,peer| # peer=["AF_INET", 59340, "127.0.0.1", "127.0.0.1"] proto,cli_port,srv_addr,cli_addr=*peer response=yield(data,cli_addr,cli_port) self.send_datagram_on_socket(serv,cli_addr,cli_port,response) if response end rescue Exception => e puts "#{e}\n #{e.backtrace.join("\n ")}" ensure end end end end |
.on_timer(periode, options) ⇒ Object
send datagram on timer
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 |
# File 'lib/minitcp.rb', line 275 def self.on_timer(periode,) Thread.new do sleep 0.1 if [:port] if $udp_socket[[:port]] sock=$udp_socket[[:port]] else sock = UDPSocket.new sock.bind("0.0.0.0", [:port]) $udp_socket[[:port]]=sock end end if [:on_timer] h=[:on_timer].call() self.send_datagram_on_socket(sock,h[:host], h[:port],h[:mess]) if h && h[:mess] && h[:host] && h[:port] end loop do nextt= (((Time.now.to_f*1000).round/periode + 1)*periode)/1000.0 delta=nextt - Time.now.to_f rep=IO.select([sock],nil,nil,delta) #puts "IO.SELECT => #{rep}" if rep Thread.new { data,peer=(sock.recvfrom(1024) rescue [nil,nil]) [:on_receive].call(data,peer,sock) if data } if [:on_receive] elsif [:on_timer] h=[:on_timer].call() self.send_datagram_on_socket(sock,h[:host], h[:port],h[:mess]) if h && h[:mess] && h[:host] && h[:port] end end end end |
.send_datagram(host, port, mess) ⇒ Object
maintain a connection to a UDP serveur, sleep timer_interconnection_ms millisecondes beetwen each reconnections
262 263 264 265 266 267 |
# File 'lib/minitcp.rb', line 262 def self.send_datagram(host,port,mess) sock = UDPSocket.new #p ["sock.send",mess, 0, host, port] sock.send(mess, 0, host, port) sock.close end |
.send_datagram_on_socket(socket, host, port, mess) ⇒ Object
268 269 270 |
# File 'lib/minitcp.rb', line 268 def self.send_datagram_on_socket(socket,host,port,mess) socket.send(mess, 0, host, port) end |