我想知道如何保留套接字的输入流并重复使用它直到应用程序关闭。 我现在所做的是在 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);
}
用于小端转换。
最佳答案
您的套接字很可能会阻塞。如果您遇到这样的问题,一个好的解决方法是将您的软件设计为轮询方法而不是中断驱动。话又说回来,软件设计模式将围绕您要实现的目标来完成。
希望对您有所帮助!干杯!
关于java - 重用套接字的输入流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6345070/