Socket.connect 在 Android 中不会抛出异常

问题描述 投票:0回答:2

如果我输入一个无意义的 url,则不会引发异常,并且我的其余代码都不会执行,甚至调用连接方法的异步任务的其余部分也不会执行。

try {
        socketCliente.connect(new InetSocketAddress("f", port), 2000);

    } catch (UnknownHostException e) {
        getError("Host doesn't exist");
        return -1;
    } catch (IOException e) {
        getError("Could not connect: The host is down");
        return -1;
    }
android sockets exception
2个回答
0
投票

添加另一个 catch 语句。

catch ( Exception e ) {
    Log.d(TAG, e.getMessage(),e);
    Toast.makeText(getApplicationContext(), "Unexpected Error:" + e.getMessage(), Toast.LENGTH_LONG).show();
}

这将写入日志并弹出一个 toast 告诉您发生了什么。


0
投票

很奇怪,你能不能再添加两行如下,看看会得到什么。

另外,在日志中,注意这两行之间的时间差。

try {
    Log.w("SOCKET", "Trying to connect...");
    socketCliente.connect(new InetSocketAddress("f", port), 2000);
    Log.w("SOCKET", "Connected. No exception");

} catch (UnknownHostException e) {
    getError("Host doesn't exist");
    return -1;
} catch (IOException e) {
    getError("Could not connect: The host is down");
    return -1;
}
© www.soinside.com 2019 - 2024. All rights reserved.