繁体   English   中英

java-无法从套接字读取

[英]java - cannot read from socket

我创建了一个ServerSocket并从其他客户端读取消息。 其中一位客户坚持认为,我的应用程序在发送消息后无法正常运行。 我设法获得了TCP跟踪,并看到它们确实发送了消息,但是我的服务器应用程序没有从套接字读取任何数据。 我得到了一个线程转储,那里似乎一切正常:

"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)

我无法从流中读取消息的原因可能是什么? 顺便说一下,其他客户不会遇到这种问题。

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

    }
}

readCount可能与流中实际可用的数据量不匹配。 如果您的客户端发送了10个字节,但您期望12个字节,则代码将被卡住,等待这两个额外的字节。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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