【发布时间】:2011-06-14 14:24:26
【问题描述】:
我想知道如何保留套接字的输入流并重用它,直到应用程序关闭。 我现在要做的是在 main 方法中创建一个线程。该线程应该在应用程序运行的所有时间内保持运行。在这个线程中,我使用套接字输入流从服务器读取数据。但我只能读取一次服务器发送的内容。之后我认为线程已经死了,或者我无法从输入流中读取。我该如何做才能让输入流读取来自服务器的内容。 谢谢。
int length = readInt(input);
byte[] msg = new byte[length];
input.read(msg);
ByteArrayInputStream bs = new ByteArrayInputStream(msg);
DataInputStream in = new DataInputStream(bs);
int cmd = readInt(in);
switch(cmd) {
case 1: Msg msg = readMsg(cmd, msg);
}
我把所有东西都放在这里,但在我的代码中,事情以不同的方式发生。
readInt 方法:
public static int readInt(InputStream in) throws IOException {
int byte1 = in.read();
int byte2 = in.read();
int byte3 = in.read();
int byte4 = in.read();
if (byte4 == -1) {
throw new EOFException();
}
return (byte4 << 24)
+ ((byte3 << 24) >>> 8)
+ ((byte2 << 24) >>> 16)
+ ((byte1 << 24) >>> 24);
}
用于小端转换。
【问题讨论】:
-
给我们看一些代码。听起来好像没有什么可以从套接字读取,所以
read()正在阻塞(等待有数据读取)。 -
我建议附上一些打印语句让你知道发生了什么,或者在一个好的调试器下运行它,这样你就可以看到什么正在运行以及它何时停止运行。如果没有代码或对问题所在的实际了解,我们不太可能为您提供太多帮助。
-
另外:你使用什么协议?您确定既不客户端也不服务器正在关闭套接字(或其流)?