重用套接字的输入流

问题描述

我想知道如何保留套接字的输入流并在应用程序关闭之前重用它。 我现在要做的是在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);
}
用于小尾数转换。     

解决方法

        您的套接字很可能被阻塞。如果遇到这样的问题,一种好的方法是为轮询方法设计软件,而不是由中断驱动。然后,将围绕您要实现的目标完成软件设计模式。 希望能帮助到你!干杯!     ,        您需要在这样的循环中调用input.read():
try {
    while(running) {
        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);
        }

     }
} catch (IOException e) { 
    //Handle error
}
完成线程需要执行的操作后,将running设置为false。请记住,input.read()将阻塞,直到套接字接收到某些东西为止。我希望这有帮助。