EventMachine将数据发送到一个客户端(来自多服务器)

时间:2013-06-18 12:28:49

标签: ruby eventmachine

我开发了多个类似

的eventmachine服务器
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

EventMachine::run {
EventMachine::start_server "127.0.0.1", 8081, EchoServer
EventMachine::start_server "127.0.0.1", 8082, EchoServer
EventMachine::start_server "127.0.0.1", 8083, EchoServer
}

现在我需要根据端口8082向客户端发送数据。如果我打开了所有连接。服务器需要将数据发送回特​​定服务器。 所以如果从8081我收到请求,我需要将它发送到8082客户端。 我该怎么发送?

2 个答案:

答案 0 :(得分:3)

根据原始问题的修改,我发布了一个新答案。

您需要为每个连接跟踪服务器port。当从端口8082建立新连接时,存储该连接直到它关闭。当您从8081端口连接的客户端获取数据时,将数据发送到之前存储的所有连接。

require 'eventmachine'

$clients = []

module EchoServer
  def initialize(port)
    @port = port
  end

  def post_init
    puts "-- someone connected to the echo server!"
    $clients << self if @port == 8082
  end

  def receive_data data
    send_data ">>>you sent: #{data}"
    # data is from a client connected by 8081 port
    if @port == 8081
      $clients.each do |c|
        c.send_data ">>>server send: #{data}"
      end
    end
    close_connection if data =~ /quit/i
  end

  def unbind
    puts "-- someone disconnected from the echo server!"
    $clients.delete self if @port == 8082
  end
end

# Note that this will block current thread.
EventMachine.run {
  # arguments after handler will be passed to initialize method
  EventMachine.start_server "127.0.0.1", 8081, EchoServer, 8081
  EventMachine.start_server "127.0.0.1", 8082, EchoServer, 8082
  EventMachine.start_server "127.0.0.1", 8083, EchoServer, 8083
}

答案 1 :(得分:2)

在您的控制台/ shell下运行telnet 127.0.0.1 8082

-> ~ $ telnet 127.0.0.1 8082
Trying 127.0.0.1...
Connected to localhost.localdomain (127.0.0.1).
Escape character is '^]'.
hello
>>>you sent: hello
quit
Connection closed by foreign host.

如果要从Ruby代码发送数据,请查看socket库。

require 'socket'

s = TCPSocket.new '127.0.0.1', 8082

s.puts "Hello"
puts s.gets     #=> >>>you sent: Hello

s.close