1

クラスでデザインしている小さなゲームで問題が発生しています。問題は、2 つのクライアントがサーバーに接続されていることです。(client1 と client2) それぞれがゲームを実行しており、最終的にウィンドウを閉じます。ゲーム ウィンドウは JDialog であるため、ウィンドウが閉じられると、ソケットを介してサーバーにメッセージが送信され、完了したことが通知されます。2 つのクライアントのどちらが最初に完了したかをサーバーに認識させたい。それらは、ソケットの OutputStream で PrintWriter を介して報告しています。私がしたことはこれでした:

    in1 = new BufferedReader(new InputStreamReader(client.getInputStream()));
    in2 = new BufferedReader(new InputStreamReader(client2.getInputStream()));
    try {
        in1.readLine();
    } catch (IOException ex) {
        Logger.getLogger(gameServer.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        in2.readLine();
    } catch (IOException ex) {
        Logger.getLogger(gameServer.class.getName()).log(Level.SEVERE, null, ex);
    }

問題は、2 番目の入力をリッスンする前に、最初の入力を待機することです。両方で同時に聞くにはどうすればよいですか?または、私の問題を他の方法で解決してください。ありがとう!

4

1 に答える 1

7

サーバー接続は次のように機能するはずです。

Server gameServer = new Server();

ServerSocket server;
try {
    server = new ServerSocket(10100);
    // .. server setting should be done here
} catch (IOException e) {
    System.out.println("Could not start server!");
    return ;
}

while (true) {
    Socket client = null;
    try {
        client = server.accept();
        gameServer.handleConnection(client);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

hanleConnection() では、新しいスレッドを開始し、作成されたスレッドでこのクライアントの通信を実行します。その後、サーバーは (古いスレッドで) 新しい接続を受け入れることができます。

public class Server {
    private ExecutorService executor = Executors.newCachedThreadPool();

    public void handleConnection(Socket client) throws IOException {    
        PlayerConnection newPlayer = new PlayerConnection(this, client);
        this.executor.execute(newPlayer);
    }

    // add methods to handle requests from PlayerConnection
}

PlayerConnection クラス:

public class PlayerConnection implements Runnable {

    private Server parent;

    private Socket socket;
    private DataOutputStream out;
    private DataInputStream in;

    protected PlayerConnection(Server parent, Socket socket) throws IOException {
        try {
            socket.setSoTimeout(0);
            socket.setKeepAlive(true);
        } catch (SocketException e) {}

        this.parent = parent;
        this.socket = socket;

        this.out    = new DataOutputStream(socket.getOutputStream());;
        this.in     = new DataInputStream(socket.getInputStream());
    }

    @Override
    public void run() {                 
        while(!this.socket.isClosed()) {                        
            try {
                int nextEvent = this.in.readInt();

                switch (nextEvent) {
                    // handle event and inform Server
                }
            } catch (IOException e) {}
        }

        try {
            this.closeConnection();
        } catch (IOException e) {}
    }
}
于 2011-10-05T12:16:42.593 に答える