我创建了一个 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 个字节,那么您的代码将因等待这两个额外字节而卡住。
关于java - 无法从套接字读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6908694/