我需要实现一个只写数据但不接收它的服务器。我发现的所有eventmachine服务器示例都始终让服务器首先接收数据,然后使用数据进行响应。我需要它才能在客户端连接后开始向客户端写入数据。
我试过在post_init中放一个循环,但这似乎不起作用......客户端连接,服务器写入,但客户端似乎永远不会收到任何东西。建议?
测试服务器:
require 'rubygems'
require 'eventmachine'
require 'time'
module TestServer
def post_init
puts "-- client connected, sending data --"
while true do
send_data "Hello from TestServer\n"
puts "sent #{Time.now.iso8601}"
end
end
end
EventMachine::run {
EventMachine::start_server "127.0.0.1", 4001, TestServer
puts 'running test server on 4001'
}
测试客户:
require 'rubygems'
require 'eventmachine'
module Forwarder
def post_init
puts "-- connected to server --"
end
def receive_data data
# none of the following is ever output
puts "in receive_data"
puts data
end
end
EventMachine::run {
EventMachine::connect '127.0.0.1', 4001, Forwarder
}
...谢谢
答案 0 :(得分:1)
感谢#eventmachine上的tmm1,得到了这个想法。客户是一样的。服务器代码是:
require 'rubygems'
require 'eventmachine'
require 'time'
module TestServer
def post_init
puts "-- client connected --"
@timer = EM::PeriodicTimer.new(0.1) {
send_data "Hello from TestServer at #{Time.now.iso8601}\n"
}
end
end
EventMachine::run {
EventMachine::start_server "127.0.0.1", 4001, TestServer
puts 'running test server on 4001'
}