1

in my game i need to check for recieving data from any of the sockets (clients) connected. the clients that are connected are saved to an array. is there a way to check for recieving from any of the clients connected? i have tried a for loop for all of the clients/sockets connected and checked for that but it doesnt seem to work. heres my for loop

    while (true) {
        try {
            for (Socket client : Server.clients) {
                Server.in = new DataInputStream(client.getInputStream());
                System.out.println("recieving information...");
                String input = Client.in.readUTF();

                Server.out = new DataOutputStream(client.getOutputStream());
                Server.out.writeUTF("connected");
                send(input);
            }
        } catch (Exception e) {
        }
    }

but i think it is only checking for one client at a time. also it doesnt help that i could be sending data wrong (or other error) so its hard to find the problem. thanks.

4

1 回答 1

1

client.in.readUTF()将阻止您的代码,直到该特定套接字具有要读取的数据,因此您的循环将被卡住。为此,您Thread每次在ServerSocket. 像这样的东西:

//receive new socket
new Thread(new Runnable() {
    public void run() {
         //while loop that waits for input on the socket
    }
}).start();

最好有一个Threads 的集合并实际命名它们,而不是像我在这里所做的那样让它们匿名,这样如果套接字连接结束,你就可以真正停止它们。

编辑:带有示例代码的Pastebin

于 2014-10-21T04:28:37.720 回答