开发者

Reusing the inputstream of a socket

开发者 https://www.devze.com 2023-03-13 08:52 出处:网络
i would like to know how to keep the input stream of a socket and reuse it until the application is close.

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 l开发者_运维百科ength = 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.


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!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消