This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Hi, I'm mainly a C++ programmer and I've been learning java for the past couple of weeks because a couple people have told me that I should. Right now, I'm trying to make an FTP Client without classes that have been made, just straight net code. As of right now, I'm using sockets and have gotten the program to log me into the ftp server and am ok with that. I've been trying to figure out the best way for me to get input from the server. My problem is with the BufferedReader's readLine function. From what I have seen so far, this will hang if the server doesn't send anything. How can I get around this? If I have too many readLines, it will just sit there and wait for something. I want to be able to process input when it comes and not have to know how many lines of data are going to come. Suggestions would be greatly appreciated! Also, am I doing it the best way? I know in C++ I can make Asyncronous sockets so when data is sent, I get a windows message and can read the data from there. Something like this would be great, but I haven't seen anything from what I've learned so far. Any things that I should look into? Thanks again!
Traditionally, Java's I/O classes only support blocking I/O, as you found out. There are some hacks to get around that in a limited way. Specifically, you can set up a background thread that close()s the resource you're trying to read from at the price of making the connection unusable; in the case of sockets you can set an SO_TIMEOUT so your call returns after blocking for a certain time; and finally, some but by no means all JVMs allow you to interrupt() an I/O thread which will cause an InterruptedIOException, again at the price of leaving you with an unusable stream. If all you want is a timeout to clean up a connection that has stalled, a TimerTask that calls close() after a while is your best bet. Combined if necessary with worker threads you should be able to meet any responsiveness requirements you might have. However, if you want full-fledged non-blocking I/O then there is no alternative for the java.nio.* new I/O packages you can find in JDK 1.4. They're great -- have a look! We can use some open source libraries that expose this new power, hint, hint - Peter
Joined: Sep 07, 2002
Thank you very much for the help! I think I might try and play around with the new nio and see how it works. Thanks again!