Android socket read method return -1

2019-09-08 12:04发布

I used faye client in my project and had a strange problem with sockets.

In this project we used SocketChannel.html#read(java.nio.ByteBuffer) method for reading from WebSocket and have -1 fo some reason.

I checked socket object and saw that isInputShutdown = false, isClosed = false, isCreated = true.

Code snippet:

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();
}

Thanks.

1条回答
Viruses.
2楼-- · 2019-09-08 12:12

It happens when server closes the connection. In this case, no exception is thrown, and the error can be checked only by the return value - a negative value indicates an error (lost connection, perhaps something else). Here is an example of such a test in AutobahnAndroid.

查看更多
登录 后发表回答