Francis Cianfrocca
12/15/2007 4:38:00 PM
[Note: parts of this message were removed to make it a legal post.]
On Dec 15, 2007 9:38 AM, James Croft <crofty_james@hotmail.com> wrote:
> hi, i'm very new to ruby and so i'd be very grateful of any help on
> this. I am writing a script that listens for UDP packets on a
> particular port. This is very easy using 'socket'. I then want to make
> a script that simulates lots of clients sending UDP packets to the
> listener. These clients should send a UDP packet from a particular port
> and then listen for a response on that same port. For this reason, I am
> trying to run each simulated client in a different thread. A simplified
> version of what i have done so far is shown below, however, when I run
> this, the client stops sending packets after the 66th one. Can someone
> explain this to me please? why is it stopping at 66? which limit am i
> hitting?
>
> Also, any suggestions on how to improve the code will be gratefully
> received. Thanks
>
Using a nonthreaded approach, I got up to about 360 packets through on a
single run. (This program requires the Ruby/EventMachine library):
#-----------------------------------------
require 'rubygems'
require 'eventmachine'
EM.epoll
SERVER = "127.0.0.1"
PORT = 1500
module Server
def receive_data data
send_data "I saw your #{data}"
end
end
module Client
def post_init
@@counter ||= 0
@@counter += 1
send_datagram "Data packet #{@@counter}", SERVER, PORT
end
def receive_data data
@@received ||= 0
@@received += 1
p "Received #{@@received}: #{data}"
end
end
EM.run {
EM.open_datagram_socket SERVER, PORT, Server
(60000..60400).each {|n|
EM.open_datagram_socket SERVER, n, Client
}
}
#-------------------------------
I did two things differently: first, I didn't introduce a delay between each
new socket. If I had, then this program would probably have scaled much
farther. And second, I used sequential port numbers rather than random ones,
to avoid trying to open an already-open port, and to avoid trying to open a
privileged one.