简体   繁体   中英

How can I read asynchronously from an inputstream?

I have a Socket with its input ad output stream. I want to use output synchronously and input asynchronously and store everything received without blocking the input.

Socket socket;
BufferedOutputStream outToServer;
DataInputStream inFromServer;
List<byte[]> incoming=ArrayList<byte[]>();


socket = new Socket();
socket.connect(new InetSocketAddress("127.0.0.1",9100), 5000);
outToServer = new BufferedOutputStream(socket.getOutputStream());
inFromServer = new DataInputStream(socket.getInputStream());

How can I add an input listener to fill incoming list with incoming data?

Basically you want to look into the java.nio packages. There is full support for doing "async", "non-blocking IO" with standard java ... since quite some years.

See here for some examples. That tutorial basically starts with code as you have written in your question ... to transform that into "async".

But to be precise: you don't need to use "nio" or "nio2"; but if you are serious about turning into that direction, then nio/nio2 provide extremely helpful features.

There is no way to read InputStream asynchronously. You have to go where this InputStream is created, and access the source of data explicetly.

You need only to pass the InputStream to the Runnable that need to be executed asynchronously. This can be done for example in the constructor.

public class ConsumeInput implements Runnable {
    private InputStream inputStream;

    public ConsumInput(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public void run() {
        // Do something with inputStream
    }

}

And in the main thread

...
ConsumeInput consumeInput = new ConsumeInput(inFromServer);
Thread t = new Thread(consumeInput);
t.start();

Obviously you can also use the new api to handle threads.

Note: this is only a skeleton code. You need to handle exceptions and closure of streams.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM