Reuse Socket Input

I would like to know how to save the socket input stream and reuse it until the application is closed. At the moment, I am creating a thread in the main method. It is assumed that this thread will work for the entire duration of the application. In this stream, I read data from the server using the socket input stream. But I can only read once what the server sends. After that, I think the stream is dead or I cannot read from the input stream. How can I make the input stream read what comes from the server. Thank.

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);
}

I put everything here, but in my code everything happens in different methods.

ReadInt method:

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);
}

Used to convert little-endian.

+3
source share
2

. , - , . , , .

, ! !

+1

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
}

, false, . , input.read() , -. , .

0

All Articles