简体   繁体   中英

java - cannot read from socket

I created a ServerSocket and read messages from different clients. One of the clients insisted that my application does not behave correctly after they sent their messages. I managed to get a TCP trace and saw that they really sent their messages, but my server application did not read any data from the socket. I get a thread dump and everything seems to be ok there:

"Reader Thread" daemon prio=3 tid=0x0ae8a000 nid=0x999 runnable [0x14525000]
   java.lang.Thread.State: RUNNABLE
        at java.net.SocketInputStream.socketRead0(Native Method)
        at java.net.SocketInputStream.read(SocketInputStream.java:129)

What may be the reason that I could not read messages from the stream? Other clients do not suffer this kind of problem by the way.

private byte[] readByte(int readCount) throws Exception {
    int b;
    int readedCount = readCount;
    byte[] receiveBuffer = new byte[readCount];
    while( true ) {
        if( readCount > 0 ) {
            b = inputStream.read(receiveBuffer, readCount - readedCount, readedCount);
        } else {
            b = 0;
        }
        if( b < 0 ) {
            throw new UnrecoverableSocketException("Connection is Broken");
        } else {
            readedCount = readedCount - b;
        }
        if( readedCount == 0 ) {
            return receiveBuffer;
        }

    }
}

It's possible the readCount does not match how much data is actually available on the stream. If your client sent 10 bytes but you were expecting 12 your code would get stuck waiting for those two extra bytes.

您的大多数readByte()方法都可以使用DataInputStream.readFully()来实现,并且您将获得数百万倍于已完成的测试量的收益。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM