【发布时间】:2015-05-26 11:45:03
【问题描述】:
我正在使用 TCP 套接字开发客户端 (Java)/服务器(C++) 应用程序。 我使用的协议由以 2 个字节开头的消息组成,这些字节定义了消息内容的类型。 所以基本上,接收线程在循环中等待接收数据。但我想使用套接字超时来通知其他主机发送数据的时间过长。
receivingSocket.setSoTimeout(durationInMilliseconds);
DataInputStream in = new DataInputStream(receivingSocket.getInputStream());
boolean success = false;
short value = 0;
do {
try {
value = in.readShort();// will throw a SocketTimeoutException in case of timeout, without 2 bytes available from the socket
success = true;
} catch (SocketTimeoutException e) {
/// do something if it happens to often. Otherwise go on with the loop
}
} catch (IOException e) {
/// abort connection in case of other problem
}
} while (!success)
现在,如果接收线程调用 in.readShort() 时套接字的缓冲区中只有一个字节可用? 这个字节是否保留在套接字的堆栈中?还是丢失了?第一种情况,下次调用 in.readShort() 的时候就可以读取了,不然好像永远丢失了……
readShort() 这里是一个例子,我的问题也代表 readInt(), ...
感谢您的帮助,
【问题讨论】:
标签: java sockets timeout datainputstream