0

ソケットから InputStream を読み取ろうとすると、ブロッキングの問題が発生します。
サーバー側のコードは次のとおりです。

public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        throw new IllegalArgumentException("Parameter : <Port>");
    }

    int port = Integer.parseInt(args[0]); // Receiving port

    ServerSocket servSock = new ServerSocket(port);
    String s;
    Socket clntSock = servSock.accept();
    System.out.println("Handling client at "
            + clntSock.getRemoteSocketAddress());
    in = new BufferedReader(
            new InputStreamReader(clntSock.getInputStream()));
    out = new PrintWriter(clntSock.getOutputStream(), true);

    while (true) {
        s = in.readLine();
        System.out.println("s : " + s);
        if (s != null && s.length() > 0) {
            out.print(s);
            out.flush();
        }
    }
}


これは、データ (文字列) を送受信しているクライアント部分です。

while (true) {
    try {
        // Send data
        if (chatText.getToSend().length() != 0) {
            System.out.println("to send :"
                    + chatText.getToSend().toString());
            out.print(chatText.getToSend());
            out.flush();
            chatText.getToSend().setLength(0);
        }

        // Receive data
        if (in.ready()) {
            System.out.println("ready");
            s = in.readLine();
            System.out.println("s : " + s);
            if ((s != null) && (s.length() != 0)) {
                chatText.appendToChatBox("INCOMIN: " + s + "\n");
            }
        }

    } catch (IOException e) {
        cleanUp();
    }
}


readLine メソッドは、上記のコードを実行しているクライアント スレッドをブロックしています。どうすればその問題を回避できますか? 助けてくれてありがとう。

4

2 に答える 2

0

readLine()EOL トークンで終わる行が必要なクライアントで使用していますが、サーバー側のコードは EOL トークンを書き込んでいません。println()の代わりに使用しprint()ます。

同時クライアントをサポートするには、サーバー上でスレッドをスピンオフして、受け入れられた接続を処理する必要があります。

while (true) {
    // Accept a connection
    Socket socket = servSock.accept();

    // Spin off a thread to deal with the client connection
    new SocketHandler(socket).start();
}
于 2012-08-29T11:37:19.960 に答える
0

readLine メソッドは、上記のコードを実行しているクライアント スレッドをブロックしています。どうすればその問題を回避できますか?

readLine はブロック操作です。複数のスレッドを使用する場合、これは問題になる必要はありません。

于 2012-08-29T11:32:42.463 に答える