1

我开发了多个 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 客户端。我该如何发送?

4

2 回答 2

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
}
于 2013-06-18T13:30:59.693 回答
2

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

-> ~ $ 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 代码发送数据,请查看socketlibrary。

require 'socket'

s = TCPSocket.new '127.0.0.1', 8082

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

s.close
于 2013-06-18T12:50:00.787 回答