有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法从socket读取数据

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

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

    }
}

共 (2) 个答案

  1. # 1 楼答案

    可能readCount与流上实际可用的数据量不匹配。如果您的客户机发送了10个字节,而您预期的是12个字节,那么您的代码将在等待这两个额外字节时陷入困境

  2. # 2 楼答案

    大多数readByte()方法都可以使用DataInputStream实现。readFully(),您将获得数百万倍于您所做测试量的好处