UDP

  • UDPSocket.openすると適当に50000番台の開いているportにbindされる
  • eventmachineでopen_datagram_socketする時は、自分で開いているportを指定する

sender.rb

#!/usr/bin/env ruby
require 'socket'

sock = UDPSocket.open

loop do
  sock.send(Time.now.to_s, 0, 'localhost', 5000)
end

sock.close

receiver.rb

#!/usr/bin/env ruby
require 'socket'

sock = UDPSocket.open
sock.bind('0.0.0.0', 5000)

loop do
  puts sock.recv(1024)
  sleep 1
end

sock.close

eventmachineでsender

#!/usr/bin/env ruby
require 'rubygems'
require 'socket'
require 'eventmachine'

class Sender < EM::Connection
  def post_init
    EM::defer do
      loop do
        send_datagram(Time.now.to_s, 'localhost', 5000)
        sleep 1
      end
    end
  end
  def receive_data data
    port, host = Socket.unpack_sockaddr_in get_peername
    puts "#{host}:#{port} - #{data}"
  end
end


EM::run do
  EM::open_datagram_socket('0.0.0.0', 5001, Sender)
end

eventmachineでreceiver

echoしてみた

#!/usr/bin/env ruby
require 'rubygems'
require 'socket'
require 'eventmachine'

class Receiver < EM::Connection
  def receive_data data
    puts data
    port, host = Socket.unpack_sockaddr_in get_peername
    puts "#{host}:#{port} - #{data}"
    send_datagram("echo> #{data}", host, port)
  end
end

EM::run do
  EM::open_datagram_socket('0.0.0.0', 5000, Receiver)
end