Android连接到WebSocket挂起

时间:2012-09-21 15:18:55

标签: android sockets timeout

在我的Android项目中,我实现了一个Faye客户端。但是,当我调用SocketChannel.socket().connect(...)时,连接挂起,下一行不会运行。就好像我没有设置超时,或者断开超时。

Thread.currentThread().setName("WebSocketConnector");
try {
    // "java.net.SocketException: Address family not supported by protocol"
    System.setProperty("java.net.preferIPv6Addresses", "false");

    mTransportChannel = SocketChannel.open();
    // mTransportChannel.configureBlocking(false);
    // the following will block until connection was established or
    // an error occurred!
    mTransportChannel.socket().connect(
            new InetSocketAddress(mWsHost, mWsPort), mOptions.getSocketConnectTimeout());
    Log.i(TAG, "Socket connected");
    // before doing any data transfer on the socket, set socket
    // options
    mTransportChannel.socket().setSoTimeout(
            mOptions.getSocketReceiveTimeout());
    mTransportChannel.socket().setTcpNoDelay(
            mOptions.getTcpNoDelay());

    return null;
} catch (IOException e) {
    Log.e(TAG, e.getMessage());
    return e.getMessage();
}

如果我这样做了:

mTransportChannel = SocketChannel.open();
mTransportChannel.configureBlocking(false);
mTransportChannel.connect(socketAddress);

SocketChannel .isConnected() return false

我不明白的问题是什么?

2 个答案:

答案 0 :(得分:0)

即使在connect()调用之前,DNS解析也可能会被阻止。将new InetSocketAddress(mWsHost, mWsPort)放在单独的行上,然后打印出结果。你有可能被困在那里。

如果不是这样,请检查您是否可以使用telnet连接到目标主机/端口:

~$ telnet host port

答案 1 :(得分:0)

此问题已解决。我的wifi连接无法访问私人资源。但我如何与Web套接字有其他问题。它是 Android socket read method return -1