Reputation: 29511
I have a small program whereby in the main thread, I ask for input from the user in the console.
System.out.print("Alternatively, enter peer's ID to connect:");
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader bReader = new BufferedReader(reader);
String peerID = bReader.readLine();
and in a separate thread I listen from my sockets' InputStream. If I receive something from this stream, i then try to "unblock" the readLine by calling System.in.close()
without waiting for the user's input. The main thread can then proceed to do something with the information obtained either from the socket's read or from the user.
Somehow it seem to work on my Mac, but if I try it on Windows, stepping through the debugger, I've found that System.in.close()
blocks and the whole program will hangs.
Any idea why and how should i unblock readline()
? Otherwise what would be a good way of rewriting the logic?
Upvotes: 0
Views: 2057
Reputation: 3327
You could try to close bReader
instead, but a sounder approach would be to use interruptible io in the nio package and possibly the Console
. I would try using the Console.read(CharBuffer), and interrupt the thread. That "should" work. Haven't tested though...
Update: But a Selector would maybe suit your purpose even better. Listen to both your socket and System.in, and act on the one that provides input?
Upvotes: 1