Mark Van De Vyver
2008-Jan-12 15:10 UTC
[Eventmachine-talk] EM beginner example code snippet
Hi Devs,
Before I post a code snippet I should get it working :)
In the following I don''t see the client quit/stop. I''d
appreciate any
suggestions.
Here it is.
== Examples
=== Robotic echo client and server
Here''s a fully-functional (and automatic) echo server and its client
written with
EventMachine - in two steps
1) Start an instance of irb in a new shell/dos command prompt
#### Start server code ####
$stderr.sync = $stdout.sync = true
require ''rubygems''
require ''eventmachine''
module EchoServer
def receive_data data
puts "Server received: #{data}"
send_data ">>>you sent: #{data}"
puts "Server sent: >>>you sent: #{data}"
(puts "CLOSING"; send_data "quit";
close_connection(true);
EM.stop) if data =~ /quit/i
end
end
EM::run{
EM::start_server "127.0.0.1", 8100, EchoServer
}
#### End server code ####
2) Start another instance of irb in a new shell/dos command prompt
#### Start client code ####
$stderr.sync = $stdout.sync = true
require ''rubygems''
require ''eventmachine''
class EchoClient < EM::Connection
def receive_data data
puts "Client Received: #{data}"
(puts "CLOSING"; close_connection(false); EM.stop) if data =~
/quit/i
end
end
cnt=0
EM::run {
emc = EM::connect "127.0.0.1", 8100, EchoClient
EM.add_periodic_timer(5) do
cnt +=1;
if cnt <= 3
emc.send_data "Message: #{cnt}"
else
emc.send_data "quit"
end
end
}
#### End client code ####
In the server shell/command window you should see:
Server received: Message: 1
Server sent: >>>you sent: Message: 1
Server received: Message: 2
Server sent: >>>you sent: Message: 2
Server received: Message: 3
Server sent: >>>you sent: Message: 3
Server received: quit
Server sent: >>>you sent: quit
CLOSING
=> nil
In the client shell/command window you should see:
Client Received: >>>you sent: Message: 1
Client Received: >>>you sent: Message: 2
Client Received: >>>you sent: Message: 3