我是ruby的新手,也许这是一个非常简单的问题.我想使用eventmachine为我的测试开发一个模拟器.以下文档中的示例我可以这样写:
require 'eventmachine'
class Server< EM::Connection
def receive_data data
send_data data
close_connection_after_writing
end
end
#Note that this will block current thread.
EventMachine.run {
EventMachine.start_server '127.0.0.1','8080', Server
}
Run Code Online (Sandbox Code Playgroud)
但我想知道是否有办法使用类的实例,如:
require 'eventmachine'
class Server< EM::Connection
attr_accessor :response
def receive_data data
send_data @response
close_connection_after_writing
end
end
server1 = Server.new
server1.response = "foo"
#Note that this will block current thread.
EventMachine.run {
EventMachine.start_server '127.0.0.1','8080', server1
}
Run Code Online (Sandbox Code Playgroud)
我尝试阅读源代码..但对我来说太难了.我肯定错过了一些东西,但我不知道怎么做这样的事情.
正如我所说,有些东西我不见了.
您可以为要实例化的类添加参数:
class Server< EM::Connection
def initialize par
puts "I'm server number#{par}"
end
def receive_data data
send_data data
close_connection_after_writing
end
end
EventMachine.run {
EventMachine.start_server '127.0.0.1','8080', Server,1
}
EventMachine.run {
EventMachine.start_server '127.0.0.1','8080', Server,2
}
Run Code Online (Sandbox Code Playgroud)
所以我将使用参数自定义实例行为
| 归档时间: |
|
| 查看次数: |
673 次 |
| 最近记录: |