wotan2009
wotan2009

Reputation: 193

Reusing the inputstream of a socket

i would like to know how to keep the input stream of a socket and reuse it until the application is close. What i do for now is creating a thread in the main method. This thread is supposed to keep running for the all time the application runs. In this thread i read data from the server using the socket input stream. But i'm able to read only one time what the server is sending. After that i think the thread is dead or i cannot read from the input stream. How can i do to keep the input stream reading what is coming from the server. Thanks.

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 here everything, but in my code things happen in different methods.

The 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 for little-endian conversion.

Upvotes: 3

Views: 1394

Answers (2)

lanoxx
lanoxx

Reputation: 13051

You need to call input.read() in a loop such as this:

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
}

Set running to false when you are finished with what ever your thread needs to be doing. Remember input.read() will block until the socket has received something. I hope this helps.

Upvotes: 0

Vern
Vern

Reputation: 2413

your socket might well be blocking. If you encounter such a problem one good way around is to design your software for a polling method rather than being interrupt driven. Then again, the software design pattern will be done around what you are trying to achieve.

Hope it helps! Cheers!

Upvotes: 1

Related Questions