Java套接字服务器无法与Ruby EventMachine客户端一起使用

时间:2012-12-26 08:04:19

标签: sockets eventmachine

我有一个非常简单的Java Socket Server:

public class NatsServer3 {
    public static void main(String[] args) throws IOException
       {
        ServerSocket serverSocket = null;

        try {
            serverSocket = new ServerSocket(10000);
            }
        catch (IOException e)
            {
            System.err.println("Could not listen on port: 10000.");
             System.exit(1);
            }

        Socket clientSocket = null;
        System.out.println ("Waiting for connection.....");

        try {
             clientSocket = serverSocket.accept();
            }
        catch (IOException e)
            {
             System.err.println("Accept failed.");
             System.exit(1);
            }

        System.out.println ("Connection successful");
        System.out.println ("Waiting for input.....");

        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
                                          true);
        BufferedReader in = new BufferedReader(
                new InputStreamReader( clientSocket.getInputStream()));

        String inputLine;

        while ((inputLine = in.readLine()) != null) {
            System.out.println("From client: " + inputLine);
            // out.println(inputLine);

            if (inputLine.equals("Bye.")) {
                break;
            } else if (inputLine.equals("PING")) {
                System.out.println("Sending PONG");
                out.println("PONG \r\n");
            } else if (inputLine.contains("CONNECT")) {
                System.out.println("Sending +OK");
                out.println("+OK\r\n");
            } else {
                System.out.println("Sending back");
                out.println(inputLine);
            }
        }
        out.close();
        in.close();
        clientSocket.close();
        serverSocket.close();
       }
}

我想通过使用基于EventMachine的客户端连接此服务器:

require 'eventmachine'

class Echo < EM::Connection
  attr_reader :queue

  def initialize(q)
    @queue = q

    cb = Proc.new do |msg|
      send_data(msg)
      q.pop &cb
    end

    q.pop &cb
  end

  def post_init
    # send_data('Hello')
  end

  def receive_data(data)
    p data
  end
end

class KeyboardHandler < EM::Connection
  include EM::Protocols::LineText2

  attr_reader :queue

  def initialize(q)
    @queue = q
  end

  def receive_line(data)
    @queue.push(data)
  end
end

EM.run {
  q = EM::Queue.new
  # hit Control + C to stop
  Signal.trap("INT") { EventMachine.stop }
  Signal.trap("TERM") { EventMachine.stop }
  EM.connect('127.0.0.1', 10000, Echo, q)
  EM.open_keyboard(KeyboardHandler, q)
}

所以问题是我可以telnet服务器并输入单词并很好地查看来自服务器的响应,但是当我使用我的EM客户端时,会发生一些奇怪的事情: 我按顺序输入了两个单词 hello1 hello2

只有当我使用Ctrl + C停止EM客户端时,服务器端才会发生任何事情,然后服务器放置: “hello1hello2”。

任何人都可以给我一些提示吗?

0 个答案:

没有答案