java - TCP 服务器响应超时

标签 java tcp

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

这是我的代码: TCP客户端

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 秒后返回。这不是套接字不活动超时 - 即套接字在空闲 3 秒后不会断开连接。

关于java - TCP 服务器响应超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28233939/

相关文章:

ios - 是否可以通过 USB 端口将 iOS 应用程序与 Windows 计算机进行通信?

java - 在运行时在 netbeans 中启用断言

java jTable : how to know the row number?

java - maven-jar-plugin mainClass - 无法找到或加载主类

java - Netty 4.0 : Spawning off, 与许多客户端/对等点维护和通信(TCP)

c++ - XMLRPCPP 异步处理多个调用?

java - 即使将 PrintStrem 设置为 UTF-8,也无法打印 unicode 字符

java - 如何使用部署描述符映射 Wildfly 中的数据源

c# - 为什么我的编码显示两次?

java - 当每个请求可能需要很长时间才能完成时,如何扩展 TCP 服务器?