2

私は、JavaでTCPにかかる時間を確認するための実験を行っています。まず、サーバーを起動します。次に、関数client_tcpを50000回以上何度も呼び出します。そして、接続にかかる時間を測定し、1バイトを送受信します。サーバーが16384を超える要求を受け取ると(場合によっては異なります)、クライアントはサーバーに接続できません。

サーバーソケットの受信バッファサイズが原因かどうかはわかりません。私の場合、ss.getReceiveBufferSize()=131072です。

コードは次のとおりです。

public synchronized void server_tcp(int port) {
    ServerSocket ss;
    Socket       so;
    InputStream  is;
    OutputStream os;

    try {           
        ss = new ServerSocket(port);
    } catch (Exception e) {
        System.out.println("Unable to connect to port " + port +
                " TCP socket.");
        return;
    }

    while (true) {
        try {
            so = ss.accept();
            is = so.getInputStream();
            os = so.getOutputStream();
            int ch = is.read();
            os.write(65);
            so.close();
        } catch (IOException e) {
            System.out.println("Something went wrong.");
        } catch (InterruptedException e) {
            System.out.println("Bye.");
        }
    }
}

public void client_tcp(String host, int port) {

    Socket       so = null;
    InputStream  is = null;
    OutputStream os = null;

    try {
        so = new Socket(host, port);
    } catch (UnknownHostException e) {
        System.err.println("Error Host not found.");
        return;
    } catch (IOException e) {
        Syste.err.println("Error Creating socket.");
        return;
    }

    try {
        os = so.getOutputStream();
        is = so.getInputStream();

        os.write(65);

        is.read();

        os.close();
        is.close();
        so.close();
    } catch (IOException e) {
        System.err.println("Error.");
        return;
    }
}

どうしたの?

ありがとうございました。

4

1 に答える 1

0

ほぼ同時に大量のソケットを作成していて、OSにはそれらを解放するのに十分な時間がありません。メソッドを呼び出すループに(実験的に調整するために)小さな遅延を追加することができますclient_tcp()

for(int i=0; i<50000; i++) {
    new SocketReuse().client_tcp("127.0.0.1", 4444);
    Thread.sleep(2); // 2 milliseconds delay
}
于 2012-12-27T02:28:46.937 に答える