0

サーバーがあり、すべてのクライアントに特定の入力 (文字列) を送信しようとしています。私のコードはここにあります:

serverSocket = new ServerSocket(SERVERPORT);
            while (true) 
                {
                    // listen for incoming clients
                    Socket client = serverSocket.accept();
                    mClients.add(client);                        
                    boolean finished = false;
                    try                             
                        {
                        for (int i=0; i<mClients.size(); i++) 
                        {
                            Socket well = mClients.get(i);
                            DataInputStream in = new DataInputStream(well.getInputStream());
                            PrintStream out = new PrintStream(well.getOutputStream());                                
                            // Print a message:
                            System.out.println("Client from : " + client.getInetAddress() + " port " + client.getPort());
                            // now get the input from the socket...                  

                                while(!finished) 
                                {
                                    String st = in.readLine();
                                    // Send the same back to client
                                    out.println(st);
                                    // Write it to the screen as well
                                    System.out.println(st);
                                    // If the input was "quit" then exit...
                                    if (st.equals("quit")) { finished = true; System.out.println("Thread exiting..."); }
                                }
                        }

私は何か間違ったことをしているようです。とにかく、接続されているすべてのソケットをベクトルに格納してから、そのうちの1つが受信した文字列を送信しようとしています。これは正しいアプローチですか?

4

1 に答える 1

0

最初の while(true) ステートメントでは、着信接続のみをリッスンし、そのクライアント接続を処理する別のスレッドを作成します。

そこから、作成した各 outPutStream を各スレッド内でグローバル ArrayList に追加できます。arrayList をループし (文字列パラメーターを使用してこのメ​​ソッドを作成します)、そのメソッド内に必要なメッセージを書き込みます。

ヘルプについては、ソケット通信に関するこのOracle チュートリアルを参照してください。

于 2012-05-12T19:42:09.680 に答える