Link to home
Start Free TrialLog in
Avatar of william007
william007

asked on

About BufferedReader

I am trying to build a mini webserver. The program below suppose to displayed the request of the client in the console, and wait for another connection...but it seems to block at
sContent = sockInput.readLine();
it seems to me that I am not using a correct approach to print the entire request from the client to the console, reason maybe the bufferedreader will not return null if there is nothing to read and simply will block there. Am I right?

What is the correction approach to display the request of the client to the console(by using bufferedreader) and not blocking at the middle if there is nothing to read?

public class Test {
      public static void main(String args[]) throws Exception {

            ServerSocket serverSocket = new ServerSocket(10000);
            while (true) {
                  Socket sock = serverSocket.accept();//Wait for connection
                  BufferedReader sockInput = new BufferedReader(
                              new InputStreamReader(sock.getInputStream()));
                  String sContent = sockInput.readLine();
                  while (sContent != null) {
                        System.out.println("here="+sContent);
                        sContent = sockInput.readLine();//<--Block here
                  }
                  
                  sock.close();
            }
      }
}
SOLUTION
Avatar of TimYates
TimYates
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of william007
william007

ASKER

Thanks,

>>that way, each new connection will get a new thread
But seems like this will result in increasing threads that last forever, am I right?

If Buffered Reader can't provide an elegance solution, I would like to open the possibility to any other approach...

ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks again,

>>When the stream closes, readLine() should return null,
I wish to know why readLine() isn't block there just like by original problem?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks:)