EventMachine没有在localhost

时间:2015-09-21 11:28:15

标签: ruby eventmachine

使用eventmachine gem我试图在localhost上发送和接收数据。以下是我的客户端和服务器文件的代码。

server.rb

class BCCServer < EM::Connection
    attr_accessor :server_socket

    def post_init
        puts "BCC Server"
    end

    def recieve_data(data)
        puts "Received data: #{data}"   

        send_data "You sent: #{data}"
    end

end

EM.run do
  EM.start_server("0.0.0.0", 3000, BCCServer)
end

client.rb

class DCClient < EventMachine::Connection
  def post_init
    puts "Sending "
    send_data "send data"
    close_connection_after_writing 
  end

  def receive_data(data)
    puts "Received #{data.length} bytes"
  end

  def unbind
    puts 'Connection Lost !'
  end
end

EventMachine.run do
  EventMachine::connect("127.0.0.1", 3000, DCClient)
end

我在单独的控制台中执行了服务器和客户端文件。以下是客户端的输出

客户端输出

Sending 
Connection Lost !

服务器输出

BCC Server
............>>>10

在服务器文件中,我已经打印了收到的数据但显示了&#34; ............&gt;&gt;&gt;&gt; 10&#34;。我在做错的地方?

谢谢

1 个答案:

答案 0 :(得分:3)

如果你看一下EM :: Connection实现

https://github.com/eventmachine/eventmachine/blob/master/lib/em/connection.rb

def receive_data data
  puts "............>>>#{data.length}"
end

方法receive_data返回您正在经历的内容。 这意味着原始方法被调用而不是你的。这意味着一件事。您尝试覆盖的方法中有拼写错误:)

在BCCServer中你有

recieve_data(data)

而不是

receive_data(data)