This is my sever
require 'rubygems'
require 'benchmark'
require 'eventmachine'
class Handler < EventMachine::Connection
def initialize(*args)
super
end
def receive_data(data)
@state = :processing
EventMachine.defer(method(:do_something), method(:callback))
#EM.defer(operation, callback)
rescue Exception => ex
LOGGER.error "#{ex.class}: #{ex.message}\n#{ex.backtrace.join("\n")}"
ensure
close_connection_after_writing unless @state == :processing
end
def do_something
#simulate a long running request
for i in 1..1000
a << rand(1000)
a.sort!
end
return "response from server"
end
def callback(msg)
self.send_data msg
@state = :closing
end
def unbind
close_connection_after_writing unless @status == :process
end
end
EventMachine::run {
EventMachine.epoll
EventMachine::start_server("0.0.0.0", 8080, Handler)
puts "Listening..."
}
This is my client
require 'rubygems'
require 'benchmark'
require 'socket'
require 'logger'
Benchmark.bm do |x|
logger = Logger.new('test.log', 10, 1024000)
logger.datetime_format = "%Y-%m-%d %H:%M:%S"
x.report("times:") do
for i in 1..10
#Thread.new do
TCPSocket.open "127.0.0.1", 8080 do |s|
s.send "#{i}th sending\n", 0
if result = s.recv(100)
logger.info result
end
puts "#{i}th sending"
#end
end
end
end
end
When i run my client , the server can not receive any data, so i change my server as follow
require 'rubygems'
require 'benchmark'
require 'eventmachine'
class Handler < EventMachine::Connection
def initialize(*args)
super
end
def receive_data(data)
operation = proc do
# simulate a long running request
a = []
for i in 1..1000
a << rand(1000)
a.sort!
end
end
# Callback block to execute once the request is fulfilled
callback = proc do |res|
send_data "data from server"
end
puts data
EM.defer(operation, callback)
end
end
EventMachine::run {
EventMachine.epoll
EventMachine::start_server("0.0.0.0", 8080, Handler)
puts "Listening..."
}
It works, i want to know why my first server can not work correctly
The problem is in the first server: you never defined
a = [], so an exception was thrown. That exception will, essentially, terminate the thread processing. The callback will never get executed and the server will never respond.Since
EM.deferworks in a thread, therescuestatement inreceived_datawill have no effect. You need a rescue in thedo_somethingmethod to catch any exceptions that happen while processing.The
ensureblock inreceive_datawill also have no effect since theEM.deferwill return immediately and that block of code will complete. The@statewill never be set to anything other then:processingat that point.You’ll want to move the
close_connection_after_writinginto the callback method itself.