【问题标题】:How to tell if the server socket is not available? [duplicate]如何判断服务器套接字是否不可用? [复制]
【发布时间】:2019-05-30 08:20:11
【问题描述】:

socket客户端正在android上运行:

try {
    socketClient = new Socket(host, port);

    //set socket input
    in = socketClient.getInputStream();
    dIn = new DataInputStream(in);

    //set socket output
    out = socketClient.getOutputStream();
    dOut = new DataOutputStream(out);

    int c = 0;
    String data = "";

    while ((c = dIn.read()) != -1) {
       //print data
    }
} catch (Exception e) {
    //close connection
}

我的服务器在 python 上运行,一切正常,除非服务器没有运行,当我尝试连接到服务器时,需要两分钟才能捕捉到服务器不可用的错误
如何减少时间,例如在 10 秒内捕获错误

【问题讨论】:

标签: java android sockets


【解决方案1】:

According to this answer

使用

Socket socketClient = new Socket();   
socketClient.connect(new InetSocketAddress(host, port),connection_time_out)

而不是

socketClient = new Socket(host, port);

connection_time_out = 限制在连接被拒绝或服务器不存在的情况下允许建立连接的时间。

【讨论】:

    猜你喜欢
    • 2013-12-31
    • 2012-10-07
    • 2013-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-22
    • 2010-12-20
    • 2013-06-04
    相关资源
    最近更新 更多