简体   繁体   中英

How to catch "event" with socket Input/Output stream in Java?

Is there any possibility to communicate with clients by events? I mean:

I have connected client, InputStreamReader and PrintWriter

in = new BufferedReader(new InputStreamReader(
                        client.getInputStream()));
out = new PrintWriter(client.getOutputStream(), true);

when I use in.readLine() server waits for incoming data. But i have this situation:

  1. Client didn't send any data
  2. Connection is still alive
  3. I need to send some data to client (but in.readLine() is still hanging process) and wait for respond

The questions are: What is the best way to handle asynchronously incoming data? I mean something like "events". Should I create thread for read and another thread for write? If i can do it in one thread, could you give an example of the code please? Is possible to abort waiting for in.readLine() ?

In my opinion having a separate thread to perform socket IO is best if you want your program to behave asynchronously. Have a look at http://en.wikipedia.org/wiki/Observer_pattern .

For a simple application, what I'll do is create a separate thread to listen for incoming data, and register 'observers' or 'event listener' to this thread. When a data comes in, notify your observers so they can perform necessary actions.

While the listener thread is idle waiting for data, your main thread still can progress normally.

Make sure you're also familiar with Java concurrency programming

Java provides non-blocking i/o through the java.nio package ( see here ). But Java's "nio" channels do not inter-operate with streams from java.io . So, if you want to use nio, you'll have to build your server with nio from the listener on down.

If you're stuck with the existing java.io streams, then you'll either have to use a thread-per-client model; or you'll need to devise a system for having a single thread (or pool of threads) manage a bunch of clients by looping over them repeatedly, polling instream.available() to figure out which ones have data ready to be handled. Of course, in this latter case, you'd want to avoid busy-looping, so some appropriate use of Thread.sleep is probably also in-order.

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