0
 require 'eventmachine'

  module EchoServer
    def post_init
      puts "-- someone connected to the echo server!"
    end

    def receive_data data
      send_data ">>>you sent: #{data}"
      close_connection if data =~ /quit/i
    end

    def unbind
      puts "-- someone disconnected from the echo server!"
    end
  end

  class Test
    attr_reader :some_value
    def start
      EventMachine::run {
      EventMachine::start_server "127.0.0.1", 8081, EchoServer
      }
    end
  end

我的问题是如何在 EchoServer 模块中获取 some_value ?类 Test 和模块 EchoServer 之间的关系是什么?

4

1 回答 1

1

如果您将 EchoServer 更改为一个类并为 some_value 添加一个 attr_accessor,那么您可以将一个块附加到启动服务器并传入该值。

#!/usr/bin/env ruby

require 'rubygems'
require 'eventmachine'

class EchoServer < EM::Connection
  attr_accessor :some_value
  def post_init
    puts "blah with #{some_value}"
  end

  def receive_data(data)
   puts "#{some_value} received #{data}"
  end

  def unbind
   puts "unbound"
  end
end

v = "some_value"
EM.run do
  EM.start_server "127.0.0.1", 8081, EchoServer do |conn|
    conn.some_value = v
  end
end

在您的示例中,Test 和 EchoServer 之间的唯一关系是您从测试类内部运行了 EM 事件循环。这对 EM 或它将如何使用 EchoServer 没有影响。

于 2010-11-14T04:17:39.080 回答