Java等待客户端数据暂停应用程序无限循环的原因

时间:2014-02-04 20:02:24

标签: java

嘿我正在尝试创建一个可以接收和发送消息给客户端的控制台应用程序。

它将接受多个客户&处理它们。

要添加新客户端,请在run方法中执行此操作:

@Override
public void run() {
    try {
        this.server = new ServerSocket(this.port);
        this.factory = new ServerFactory(this.server);
        System.out.println("Server runs and now waiting for clients");
        this.runClientHandler();
        Socket client;
        while ((client = this.server.accept()) != null) {
            this.handler.addClient(this.factory.createClient(client));
            System.out.println("done");
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}

但是“完成”将永远不会被打印,因为这个客户端的消息无限循环:

public void handleClient() throws IOException {
    byte[] buffer = new byte[5*1024];
    int read = -1;
    byte[] data;
    String message;
    while ((read = this.socket.getInputStream().read(buffer)) > -1) {
        data = new byte[read];
        System.arraycopy(buffer, 0, data, 0, read);
        message = new String(data, "UTF-8");
        System.out.println("Client message: " + message);
    }
}

handleClient()方法将在handleClients.add()的Thread-2中运行:

public void addClient(Client c) throws IOException {
    c.writeMessageStream("hey");
    System.out.println("New client!");
    this.clients.add(c);
            //prints here
    c.handleClient();
            //never reaches this..
}

如何忽略while循环并让while循环运行时程序执行而不为每个客户端创建一个新线程?

2 个答案:

答案 0 :(得分:0)

检查NIO选择器。它们是JDK中Java NIO的一部分。或者您可以使用Netty或(更糟糕的)Apache MINA等开箱即用的解决方案。

答案 1 :(得分:0)

您的代码将无法处理多个客户端,因为它从接受连接的同一线程为客户端提供服务。通常,客户端连接应由不同的线程处理,您可能希望使用异步IO,以便可以从单个线程处理多个连接。您应该使用简化所有这些的Netty。以下是一些示例程序http://netty.io/5.0/xref/io/netty/example/telnet/package-summary.html