我想知道如何保持套接字的输入流并重用它,直到应用程序关闭。 我现在所做的是在主要方法中创建一个线程。这个线程应该在应用程序运行的整个过程中保持运行。在这个线程中,我使用套接字输入流从服务器读取数据。但是我只能读一次服务器发送的内容。之后,我认为线程已经死亡,或者我无法从输入流中读取。我该如何保持输入流读取来自服务器的内容。 谢谢。重新使用套接字的输入流
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()'被阻塞(等待那里有数据读取)。 – 2011-06-14 14:26:19
我建议你使用一些打印语句,让你知道发生了什么,或者在一个好的调试器下运行它,这样你就可以看到什么在运行,什么时候停止运行。没有关于问题的代码或实际的知识,我们不可能非常帮助你。 – 2011-06-14 14:26:52
另外:你使用什么协议?你确定*既不*客户*也不*服务器正在关闭套接字(或其流)? – 2011-06-14 14:27:44