简体   繁体   中英

Reading from a socket in a while loop

I want to implement the following functionality

while (true)
{
if client sends something 
process it

else wait till something is send }

I have tried the following but it didn't work , it process one thing and then stop working can anyone help me? I have searched for such a case here but I didn't find anything . I would appreciate it if anyone can give an example of how to read from the socket inside a while loop as in the above description .

            BufferedReader inFromClient = new BufferedReader(new InputStreamReader(client.getInputStream()));
            DataOutputStream outToclient =new DataOutputStream(client.getOutputStream());
            while (true){
                if ((request=inFromClient.readLine())!=null){


                        System.out.println("ser "+request);         
                        msg1= new msgs();
                        if(msg1.IsListReq(request))
                        {
                               System.out.println("Ser :List req");



                               for (int i = 0; i <listOfFiles.length ; i++) 
                               {

                                    if (listOfFiles[i].isFile()) 
                                     {

                                         files[i] = listOfFiles[i].getName();
                                     }

                               }

                                //prepare the respones
                                msg1.MakeFileListResponse (files);
                                outToclient.writeBytes(msg1.getMsg()+'\n');

                        } // end of processing List Request
                    } // end of first if statement
                 } end of while loop

You should have a condition to break your while loop or it will loop forever and your program will crash. This could be the problem you have.

Right now, you have an infinite loop. This differs from "read as long as there is input available" in that it will continue to read after input is no longer available.

Try something like this:

do
{
    request = inFromClient.readLine();
    if (request != null)
    {
        // do stuff.
    }
} while (request != null);

The example above will stop reading when input is no longer available from the input stream.

For information about java and sockets check out the Oracle Java Socket Tutorial . The work you describe will reside on a server.

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