使用Ruby套接字的TCP服务器可以工作但不使用eventmachine

时间:2012-02-28 09:49:26

标签: ruby eventmachine

我使用下面的代码写了一个TCP服务器。这是通过GSM网络从远程GPS传感器接收GPS位置数据。

require 'socket'

server = TCPServer.open(2000) # Listen on port 2000
sockets = [server]                              # An array of sockets we'll monitor
log = STDOUT                                    # Send log messages to standard out
   while true
ready = select(sockets)
readable = ready[0]

readable.each do |socket|
  if socket == server
    client = server.accept
    sockets << client
       log.puts "Accepted connection from #{client.peeraddr[2]}"
       while msg = client.gets
       puts msg
  end
else
  input = socket.gets

    if !input
      log.puts "Client on #{socket.peeraddr[2]} disconnected"
      sockets.delete(socket)
      socket.close
      next
    end

    input.chop!
    if (input == "quit")
      socket.puts("Bye");
      log.puts "Closing connnection to #{socket.peeraddr[2]}"
      sockets.delete(socket)
      socket.close
    else
      socket.puts(input.reverse)
    end
   end
  end
 end

然后我用Eventmachine写了一个。代码如下:

require 'eventmachine'

module EchoServer
 def post_init
  puts "-- someone connected to the echo server!"
end

def receive_data data
    puts data
end

def unbind
  puts "-- someone disconnected from the echo server!"
end
end

EventMachine::run {
   EventMachine::start_server "127.0.0.1", 2000, EchoServer
 }

但是,此事件机器代码不会接收也不会显示数据。 Eventmachine代码的任何部分都是错的?

由于

1 个答案:

答案 0 :(得分:2)

我认为你的问题是你只是在监听localhost,试试这个:

EM::run do
   EM.start_server "0.0.0.0", 2000, EchoServer
end