Android套接字读取方法返回-1

时间:2012-09-28 08:38:12

标签: android sockets faye

我在我的项目中使用faye client并且套接字出现了一个奇怪的问题。

在这个项目中,我们使用SocketChannel.html#read(java.nio.ByteBuffer)方法从WebSocket进行阅读并拥有 -1出于某种原因。

我检查了套接字对象并看到了isInputShutdown = falseisClosed = falseisCreated = true

代码段:

System.setProperty("java.net.preferIPv6Addresses", "false");   
mTransportChannel = SocketChannel.open();        
InetSocketAddress socketAdd = new InetSocketAddress("172.20.71.4", 9292);    
boolean resolve = socketAdd.isUnresolved();    
mTransportChannel.socket().connect(socketAdd, 6000);   
Log.i("TEST", "Socket connected");
mTransportChannel.socket().setSoTimeout(6000);
mTransportChannel.socket().setTcpNoDelay(true);
mBuffer = new ByteBufferOutputStream(1000 + 14, 4 * 64 * 1024);
WebSocketMessage.ClientHandshake hs = new WebSocketMessage.ClientHandshake(
                "172.20.71.4" + ":" + "9292");
hs.mPath = "/faye/services/chat-123456789-123456";
hs.mQuery = null;
hs.mSubprotocols = null;
sendClientHandshake(hs);
int written = mTransportChannel.write(mBuffer.getBuffer());
mFrameBuffer = ByteBuffer.allocateDirect(1000 + 14);
int len = mTransportChannel.read(mFrameBuffer);
Log.d("tset", Integer.toString(len));


/**
 * Send WebSocket client handshake.
 */
private void sendClientHandshake(WebSocketMessage.ClientHandshake message) throws IOException {
    // write HTTP header with handshake
    String path;
    if (message.mQuery != null) {
        path = message.mPath + "?" + message.mQuery;
    } else {
        path = message.mPath;
    }
    mBuffer.write("GET " + path + " HTTP/1.1");
    mBuffer.crlf();
    mBuffer.write("Host: " + message.mHost);
    mBuffer.crlf();
    mBuffer.write("Upgrade: WebSocket");
    mBuffer.crlf();
    mBuffer.write("Connection: Upgrade");
    mBuffer.crlf();

    mBuffer.write("Sec-WebSocket-Key: " + newHandshakeKey());
    mBuffer.crlf();

    if (message.mOrigin != null && !message.mOrigin.equals("")) {
        mBuffer.write("Origin: " + message.mOrigin);
        mBuffer.crlf();
    }

    if (message.mSubprotocols != null && message.mSubprotocols.length > 0) {
        mBuffer.write("Sec-WebSocket-Protocol: ");
        for (int i = 0; i < message.mSubprotocols.length; ++i) {
            mBuffer.write(message.mSubprotocols[i]);
            mBuffer.write(", ");
        }
        mBuffer.crlf();
    }

    mBuffer.write("Sec-WebSocket-Version: 13");
    mBuffer.crlf();

    mBuffer.crlf();
}

感谢。

1 个答案:

答案 0 :(得分:1)

服务器关闭连接时会发生这种情况。在这种情况下,不会抛出任何异常,并且只能通过返回值检查错误 - 负值表示错误(连接丢失,可能还有其他内容)。以下是AutobahnAndroid中此类测试的example