TCP 服务器响应超时

TCP Server response timeout

我的任务是让一个简单的 TCP 客户端超时。客户端按预期工作,但是当客户端在 3 秒或更长时间内未收到输入时,我似乎无法让客户端超时。 我对 SO_TIMEOUT 有基本的了解,但无法在这里发挥作用。 请帮忙

这是我的代码: TCPClient

private static final String host = "localhost";
    private static final int serverPort = 22003;

    public static void main(String[] args) throws Exception
    {

        try
        {
            System.out.println("You are connected to the TCPCLient;" + "\n" + "Please enter a message:");
            BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
            @SuppressWarnings("resource")
            Socket client = new Socket(host, serverPort);
            client.setSoTimeout(3000);
            while(true)
            {
                DataOutputStream outToServer = new DataOutputStream(client.getOutputStream());
                BufferedReader inFromServer = new BufferedReader(new InputStreamReader(client.getInputStream()));
                String input = inFromUser.readLine();
                outToServer.writeBytes(input + "\n");
                String modedInput = inFromServer.readLine();
                System.out.println("You Sent: " + modedInput);
                try
                {
                    Thread.sleep(2000);
                }
                catch(InterruptedException e)
                {
                    System.out.println("Slept-in");
                    e.getStackTrace();
                }
            }
        }
        catch(SocketTimeoutException e)
        {
            System.out.println("Timed Out Waiting for a Response from the Server");
        }
    }

setSoTimeout 并不像您想象的那样。来自 Javadoc:

With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time.

这是从套接字读取超时,所以即使没有数据,reads() 也会在 3 秒后 return。这不是套接字不活动超时 - 即套接字在空闲 3 秒后不会断开连接。