我有一个非常简单的 Java Socket 服务器,如下所示:
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)
}
所以问题是我可以远程登录服务器并输入单词并很好地看到服务器的响应,但是当我使用我的 EM 客户端时,发生了一些奇怪的事情:我依次输入了两个单词 hello1 hello2
仅当我使用 Ctrl+C 停止 EM 客户端时,服务器端没有任何反应,然后服务器输入:“hello1hello2”。
任何人都可以给我一些提示?