0

我在我的项目中使用了faye 客户端,并且遇到了一个奇怪的套接字问题。

在这个项目中,我们使用SocketChannel.html#read(java.nio.ByteBuffer)了读取的方法WebSocket并且有 -1一些原因。

我检查了套接字对象并看到了isInputShutdown = false, isClosed = false, isCreated = 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();
}

谢谢。

4

1 回答 1

1

当服务器关闭连接时会发生这种情况。在这种情况下,不会抛出异常,只能通过返回值来检查错误——负值表示错误(丢失连接,可能是其他原因)。这是 AutobahnAndroid 中此类测试的示例

于 2012-09-28T19:22:28.917 回答