class UDPAgent

Public Class Methods

on_datagramme(host,port) { |data,cli_addr,cli_port| ... } click to toggle source

recieved UDP datagramme, bloc can ellaborate a reply, which will be sending to client

# 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) click to toggle source

send datagram on timer

# File lib/minitcp.rb, line 275
def self.on_timer(periode,options)
  Thread.new do 
    sleep 0.1
    if options[:port]
      if $udp_socket[options[:port]]
         sock=$udp_socket[options[:port]]
      else
        sock = UDPSocket.new
        sock.bind("0.0.0.0", options[:port])
        $udp_socket[options[:port]]=sock
      end
    end
    if options[:on_timer]
        h=options[: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])
             options[:on_receive].call(data,peer,sock) if data
        } if options[:on_receive]
      elsif options[:on_timer]
        h=options[: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) click to toggle source

maintain a connection to a UDP serveur, sleep timer_interconnection_ms millisecondes beetwen each reconnections

# 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) click to toggle source
# File lib/minitcp.rb, line 268
def self.send_datagram_on_socket(socket,host,port,mess)
      socket.send(mess, 0, host, port)
end