【问题标题】:Socket timeout not working套接字超时不起作用
【发布时间】:2014-01-13 21:03:38
【问题描述】:

我有一个在 C# 机器上运行的 TCP 套接字。我需要通过服务器 IP 和端口从 Android 连接该服务器套接字,如下所示:

InetAddress serverAddr = InetAddress.getByName(serverIp);
Socket socket = new Socket(serverAddr, serverPort);
socket.setSoTimeout(10*1000);

如果 c# 机器没有在 Android 上运行套接字,它会挂起:

Socket socket = new Socket(serverAddr, serverPort);

我需要实现 5 秒作为超时,如果它在这个 ip 上找不到服务器套接字,它可能只是超时。

请思考..

【问题讨论】:

    标签: android sockets timeout


    【解决方案1】:

    希望对您有所帮助:

    使用无参数构造函数创建套接字,如下所示:

    Socket socket = new Socket();
    

    然后使用

    socket.connect(remoteAddress, timeout);
    

    另一种方式:

    Socket socket= new Socket();   
    socket.connect(new InetSocketAddress(hostip,port_num),connection_time_out); 
    

    【讨论】:

    • Socket socket= new Socket(); socket.connect(new InetSocketAddress(hostip,port_num),connection_time_out);完美地为我工作。谢谢巴文
    【解决方案2】:
    InetAddress serverAddr = InetAddress.getByName(serverIp);
    Socket socket = new Socket();
    socket.connect(serverAddr, timeout);
    

    【讨论】:

    • java.net.Socket 不包含这样的构造函数:new Socket(serverAddr, serverPort, timeout)。请问有什么进一步的帮助吗?
    猜你喜欢
    • 2018-07-20
    • 1970-01-01
    • 2013-05-29
    • 1970-01-01
    • 2019-07-22
    • 1970-01-01
    • 2019-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多