Question about sockets

S

stathis gotsis

Hello,
I have the following segment of code in a program:

in = new BufferedReader(new InputStreamReader(
mailSocket.getInputStream()));

,in which a mailSocket is an object of Socket class.

Later on, i am using this expression:

while ((serverOutput = in.readLine()) != null)
System.out.println(serverOutput);

/*other stuff here*/

,wanting to print all the lines available on my end of the Socket at the
time being. This readLine() method is blocking, thus preventing the program
from getting on to the other stuff. How can i avoid this?

Thank you for any help
 
C

Chris Smith

stathis gotsis said:
while ((serverOutput = in.readLine()) != null)
System.out.println(serverOutput);

/*other stuff here*/

,wanting to print all the lines available on my end of the Socket at the
time being. This readLine() method is blocking, thus preventing the program
from getting on to the other stuff. How can i avoid this?

If you don't want blocking I/O, you can't use readLine at all. You need
to use a SocketChannel and a CharBuffer to do the I/O. The code looks
considerably different, and will be tougher to understand... but in
conjunction with intelligent use of java.nio.Selector, it's potentially
the most efficient way to do things.

Another way out of the problems of blocking I/O is to continue to use
blocking I/O, but also use multiple threads. You can spawn a new thread
to read from each possible client of the socket. This is clearly not
scalable to very high numbers of concurrent connections, but it's a heck
of a lot easier than the NIO way.

--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top