ZeroMQ驱动的服务器在一段时间后停止响应

时间:2011-11-21 20:23:40

标签: ruby eventmachine zeromq

我正在研究如何将ZeroMQ与EventMachine一起使用。 为了测试,我在ruby(echo客户端服务器)中编写了一个小程序,其中我使用了XREQ和XREP套接字。客户端应用程序正在向服务器发送消息(连续数字)并将其返回到响应中。发送之间的间隔是0.1秒。 一切正常......直到某个时刻。当前数量达到约400时,服务器只是冻结,不再响应客户端。我在几台计算机上测试了这个,但仍然遇到了这个奇怪的问题。

代码很简单:

server.rb

require 'rubygems'
require 'bundler/setup'
require 'em-zeromq'

Thread.abort_on_exception = true

ADDRESS = 'tcp://127.0.0.1:2091'

class EMServerHandler
  attr_reader :received
  def on_readable(socket, messages)
    client_identity = messages.shift.copy_out_string #getting client identity from the 1st part of the message
    messages.shift #skip the delimeter
    messages.each do |m|
      msg = m.copy_out_string
      puts "server received from #{client_identity}: " + msg
      socket.send_msg("#{client_identity}",'',"#{msg}") #echo message back to the client
    end
  end
end

trap('INT') do
  EM::stop()
end

puts "Program started (with zmq #{ZMQ::Util.version.join('.')})."

EM.run do
EventMachine.epoll
  ctx = EM::ZeroMQ::Context.new(1)  
  server = ctx.bind(ZMQ::XREP, ADDRESS, EMServerHandler.new, {:identity => "server"})
end

client.rb

require 'rubygems'
require 'bundler/setup'
require 'em-zeromq'

Thread.abort_on_exception = true

ADDRESS = 'tcp://127.0.0.1:2091'

class EMClientHandler
  attr_reader :received
  def on_readable(socket, messages)
    messages.shift #skip the delimeter
    messages.each do |m|
      puts "client recieved: " + m.copy_out_string
    end
  end
end

trap('INT') do
  EM::stop()
end

puts "Program started (with zmq #{ZMQ::Util.version.join('.')})."

EM.run do
  EventMachine.epoll
  ctx = EM::ZeroMQ::Context.new(1)
  puts "client"
  puts "enter client name >> "
  identity = gets.strip
  client = ctx.connect(ZMQ::XREQ, ADDRESS, EMClientHandler.new, {:identity => identity})
  client.send_msg('', "hello from client #{identity}")
  count = 0
  EM::PeriodicTimer.new(0.1) do
    client.send_msg('', "#{count += 1}")
  end
end

请帮我弄清楚原因。

2 个答案:

答案 0 :(得分:1)

最后我发现这个问题只在使用ruby 1.9.3p0时出现,所以感觉这是ruby版本的bug。 使用ruby 1.9.2,一切都像魅力一样。

答案 1 :(得分:1)

垃圾收集器正在收集您的ZeroMQ上下文。

您需要将呼叫转移到EM::ZeroMQ::Context#new循环之外的EM

请参阅README