Can't break out of a while loop

Hi, I am doing a networking course, for which an assignment was to write an echo client and server. I did the assignment in Java and it works just fine. However, there is something I don't understand that is bugging me. I wanted a way to stop the server by either detecting when the client entered "quit" or when the user of the server entered "quit". This was not part of the assignment, but after trying many different things I really want to know (1) what I am doing wrong and (2) what the correct way to do things would be.
I tried to put an "if" clause within the while loop so that if the client entered "quit" the server would detect that, close the socket connections, and break the while loop. But... it seems that I have done this wrong and I am not sure why.
(Note - I am not a Java programer - just a beginner, and the course in question isn't a programming course. I did the program below by following some brief guidelines/tutorial. I don't even have any books on Java to consult right now - just ordered few from Amazon for any future projects.)
The code:
// EchoServer.java     - a simple server program. It listens on a predetermined port for an incoming connection.
//                After a client connects they can input a line of text and
//                the server will echo the exact same line back.
import java.io.*;
import java.net.*;
public class EchoServer {
     protected static int DEFAULT_PORT = 3004;
     public static void main (String args[]) throws Exception {
          int portNumber;          
          try {
               portNumber = Integer.parseInt(args[0]);
          } catch (Exception e) {
               portNumber = DEFAULT_PORT;
          ServerSocket myServer = null;
            try{
               myServer = new ServerSocket(portNumber);      
               System.out.println("Echo Server started. Listening on port " + portNumber);
          } catch (IOException e) {
               System.out.println("Could not listen on port: " + portNumber);
               System.out.println(e);
          Socket clientSocket = null;                         
          try{          
                 clientSocket = myServer.accept();
          } catch (IOException e) {
                 System.out.println("Accept failed:  " + portNumber);
               System.out.println(e);
          BufferedReader input = null;     
          PrintWriter output = null;
          try {               
               input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
               output = new PrintWriter(clientSocket.getOutputStream(), true);
          } catch (IOException e) {
               System.out.println(e);
          String theLine;     
          while(true){
               theLine = input.readLine();
               output.println(theLine);     
               output.flush();
                    if (theLine.equals("quit"))  {
                         input.close();
                         output.close();
                         clientSocket.close();
                         myServer.close();     
                         break;
                    }     // end if
          }     // end while     
     }     // end main
}          // end EchoClient

A few observations:
- You might as well exit after you have caught your exceptions, since none of the conditions I see would allow your program to run properly afterwards. You can either do that by a System.exit(int) or a return;
- Although this s an example program, you should take advantage of doing things right. Addining a try-finally would be good for tidying things up. First declare your variables before the main try, otherwise the finally won't be able to do its job. For example (this won't compile as is):
Socket clientSocket = null;
ServerSocket myServer = null;
InputStream in = null;
OutputStream out =null;
try {
  String theLine = null;     
  while( (theLine = input.readLine()) != null ){
    output.println(theLine);     
    output.flush();
    if (theLine.equals("quit"))  {
       break;
  }     // end while
} catch ( IOException ex ) {
  ex.printStackTrace();
} finally {
  if ( in != null ) {
     in.close();
  if ( out != null ) {
     out.close();
  // add other conditions to close other closeable objects
}The reasoning is that if an exception were ever to happen you would be sure that the clean up would be done. In your current example you may risk having an inputstream left open. Also note that BufferedReader.readLine() returns null when its arrived at the end of its content.

Similar Messages

  • Break out of a while loop from outside the loop

    Hello,
    I have an application where I have some nested while loops. Is it possible to break the innermost loop from a control that is outside of the inner loop? My inner loop is running a scan and read operation on the serial port and is reading data as it somes in. I need this loop to break when the user presses a button located in one of the outer loops so that another section of the vi can execute. Thanks in advance.
    Greg
    Gregory Osenbach, CLA
    Fluke

    Greg,
    You should place the terminal of the button in the innermost loop and wire out from there to the other locations the value is needed. If these are nested loops, the controls will not get read until the outer loop iterates again and this can only happen if the inner loop has ended anyway. Thus your scheme will not work.
    Alternatively, you can place the control in a loop that executes in parallel,then use local variables of it in the other locations, but the above solution is better.
    LabVIEW Champion . Do more with less code and in less time .

  • Can't break out of the restore loop on my iPod Touch.

    I've tried different USB ports, different USB cables, verified and repaired my permissions,and I have no third party security that I know. I unfortunatly do not have a diffrent computer to try. I'm guessing that is the answer I will get. But if anyone has some advice, I would love to hear it.

    Maybe:
    Restore loop (being prompted to restore again after a restore successfully completes)
    Troubleshoot your USB connection. If the issue persists, out-of-date or incorrectly configured third-party security software may be causing this issue. Please follow Troubleshooting security software issues. .
    Next try placing in DFU mode and then restoring.
    How to put iPod touch / iPhone into DFU mode « Karthik's scribblings
    Then try restoring on another computer.
    Last, make an appointment at the Genius Bar of an Apple store.
    Apple Retail Store - Genius Bar

  • How to out from infinite while loop in sub VI

    Dear Sir,
    how to out from infinite while loop in sub VI from main VI
    attached photo for solution but I can't understand it and i can't find the function in photo 
    please help
    Attachments:
    stop_subVI_frm_main.JPG ‏36 KB

    Asking how to get out of an infinite loop is like asking how to find the end of a circle. I'm not trying to be sarcastic but by definition, if there is a way out of the loop, then it is not infinite. I think what you are asking is how to avoid creating an infinite loop. Is there something about the suggestions you have been given that you do not like? My favorite suggestion is the notifier but maybe you just need an example. Turn on context help and read about the notifier functions in the code below.
    This is your top level VI
    And this is your subVI
    If this seems too complex then a global variable will work too. But what seems simpler can cause much more complex bugs. You can code fast and spend lots of time debugging or you can code slow and spend less time debugging. Personally I perfer writing productive code than looking for bugs any time.
    =====================
    LabVIEW 2012

  • How do I store 4 hours of data and get it out of the "while loop" into a spreadshee​t file for documentin​g purposes? "See additional Text for additonal info"

    What a have is a VI that uses the following SUbvi's, starts with FP OpenVI, then FP Create TagVI, into a "While Loop" which contains a FP ReadVI outputting data into a Index ArrayVI outputting to a Display (DBL). This shows the output of a FP-AI-100 monitoring a 9v battery. I have to monitor this battery for a 4 hour period my problem is storing the 4 hours of data and getting it out of the "while loop" into a "Write to Spreadsheet File VI" all I seem to accomplish is just one data sample which I get into a spreed ship file with no problem. I just can't get 4 hours worth. By the way this is my first VI and I'm self
    trained so have mercy.

    I figured it out thanks.
    John Morris
    Glendinning Marine

  • How do I store 4 hours of data and get them out of the "while loop" into a spreadsheet file for documenting purposes? "See additional Text for additonal info"

    What a have is a VI that uses the following SUbvi's, starts with FP OPENvi, then FP Create Tagvi, into a "While Loop" which contains a FP READvi outputting data into a INDEX ARRAYvi outputting to a Display (DBL). This shows the output of a FP-AI-100 monitoring a 9v battery. I have to monitor this battery for a 4 hour period my problem is storing the 4 hours of data and getting it out of the "while loop" into a "Write to Spreadsheet File vi" all I seem to accomplish is just one data sample which I get into a spreed ship file with no problem. I just can't get 4 hours worth. By the way this is my first VI and I'm sel
    f trained so have mercy.

    I figured it out Thanks.
    John Morris
    Glendinning Marine

  • What is the maximum size of indexed array that can be created during execution of while loop?

    Hello,
    I am using a ring acquisition to take in images. If i write them as files in the loop, it slows down the acquisition unacceptably. Therefore i am converting image to array and storing the array until the acquisition is complete and then reading the array and converting back to image to save. The program sometimes runs out of memory (after a couple of minutes). Can anyone think of a way where i can store the array/images within the execution (without losing image information), without slowing it down and to avoid this memory problem?
    I have included the VI.
    Thanks in advance for any help or advice.
    kindest regards,
    FraserD
    Attachments:
    LL_Ring_in_IMAQ_8_bit_array_then_write_as_png.vi ‏94 KB

    When you build the array of pictures you do it using auto-indexing out of a while loop. That means that memory is aquired for a copy of the previous picture array and the array is rebuilt on every iteration, this is slow and requires a lot of extra memory.
    If you want to speed things up try initializing a shift register with a 3D array of a size that will be able to hold a certain number of pictures, then replace the "pages" as new pictures are aquired, replace operations do not require copying of the previous array and will thus be much much faster. The difference is exeptional when dealing with large arrays/amounts of data.
    Now, the shift register buffer could be built into a functional global, and you can add a push/pop logic to it so that you can have a p
    arrallell loop that works on writing the elements to disk. You could use a que for this, but I think even though you specify a size limit to the que it still aquires memory as new elements are added (correct me if I'm wrong people...:-)), so a functional global acting as a circular buffer og fixed size frame for a que should be better.
    MTO

  • How can I transfer data between two while loops in parallel

    Hello,
    I have two while loops in parallel and I want to transfer data from the first to the second loop. The problem isthat data are transfered only when the first loop ends. I tried with queue but it doesn't work. How can I do, preferentially without global variable ?
    Thanks.

    I join a very simplified VI's because the real works with PXI, RT, ...
    When you run the "secondVI.vi", no data comes in array from the "firstVI.vi".
    As I said in my first message, I tried with queue too but it doesn't work, because when the terminal go out from the while loop, while loop have to be ended to send data.
    Attachments:
    transfer_data.zip ‏20 KB

  • Trying to purchase music, it sends me to verify my acct info, I do that hit done, it asks if I still want the purchase, I select Yes and it sends me back to verify billing information.  How can I get out of this darn loop and make my purchase?

    In itunes Store. Trying to purchase music, it sends me to verify my acct info, I do that, hit done, it asks if I still want the purchase, I select Yes and it sends me back to verify billing information.  How can I get out of this darn loop and make my purchase?

    Hi itunes for windows,
    If you are being repeatedly prompted to authorize iTunes, even after you have already done so, you may find the following article helpful:
    Apple Support: iTunes repeatedly prompts to authorize computer to play iTunes Store purchases
    http://support.apple.com/kb/ts1389
    Regards,
    - Brenden

  • Can you lock out the Ipad while it is traveling down the road?

    I would like to put an Ipad in my trucks, but I can't trust the drivers to not use it while they are driving. Is there a way to lock out the Ipad while the vehicle is moving?

    Perhaps a Workstation Associated app that just pushed an invalid value for the
    GINA.DLL
    Either Remote Regedit or another Force-Run app could restore this to a correct
    value.
    Needs testing to make sure you can fix what you break, but this would lead
    everything intact.
    Marcus Breiden wrote:
    > On Mon, 23 May 2005 19:05:23 GMT, [email protected] wrote:
    >
    > > I am not sure how this can be performed. We currently do something
    > > similar with NEW XP PCs that have no local user accounts on them yet
    > > (basically we enable login restrictions under the DLU policy - if the
    > > workstation can't create a local user account for the user, they can't
    > > log into the network or the PC). That solution would not work in this
    > > case though since the local accounts would already be created on the PC.
    >
    > hmmm.... I would create an application and associate it to the wks, make it
    > force run..
    >
    > in that app remove / or change the Tree for the workstation manager... this
    > will disable all policy management (also DLU)...
    >
    > in case your accounts are locally on that box you would have to do some
    > more stuff to get around your problem...
    > --
    >
    > Marcus Breiden
    >
    > Please change -- to - to mail me.
    > The content of this mail is my private and personal opinion.
    > http://www.edu-magic.net
    Craig Wilson
    CNE3, 4, 5 - MCSE - CCNA
    NSC Sysop (http://support.novell.com/forums/)
    Tech Writer - http://www.ithowto.com
    (I Peter 4:10)

  • How to close FPGA reference out from different while loop

    Hi Friends,
                  I`ve different while loop which performs the FPGA read port on different loops I`ve the FPGA out on every terminal at the end of the while loop. I`ve just connected the merge error function in which all the error out of the FPGA are combined and given to simple error handler. How to close the FPGA Reference.

    Can you attach your VI?  I'm not clear on what you mean.  Are you saying that you are using the FPGA reference which is passed into multiple loops, and then continuing the reference wire to pass the ref out of each of the multiple loops?
    If that is the case, I don't believe you can't merge references like you can error clusters.  You will just need to wire one of the reference to the close FPGA VI.  Additionally though, I'd recommend that you use your error clusters in some manner to ensure data flow so that all the other loops stop first, and you are sure you are closing the reference after all the other loops are done with the ref. 

  • How to get the loop sequence time (i) out of the while loop in the sub-vi to the main vi?

    I tried to search for the answer but no much luck.  My situation is that I used a sub-vi containing a while loop in my main vi. Now I need to see the while loop sequence number (i) from that sub-vi in my main vi.  In the sub-vi I have the indicator to show this loop sequence flawlessly, but that's inside the loop itself.  If I use this indicator as a terminal in the sub-vi, I can only see the last sequence number in the main vi after the loop finished its execution.
    Is there a way to accomplish this? Thanks.

    Hi nobody,
    well easiest (but error prone) way is to use globals to move data from subvi to main vi. You can also give the reference of the main vi indicator to the subvi to write to a "value" property node. You can also use queues, and there are other techniques too
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome

  • I tried to update to mavericks which made my MacBook unworkable. I reformatted with my startup disc and now have reloaded my computer from a backup on time capsule. I keep getting a panic screen on start up and can't get out of this perpetual loop?

    I tried to update to mavericks but it crashed my system. I reformatted and restored from time capsule but have a panic screen I can't get out of.

    Read this thread.
    https://discussions.apple.com/message/22935993#22935993
    Linc Davis is a very smart guy on here, and his recommendation in that thread is to reinstall the OS. I'd suggest a backup first.

  • Can I make an awkwardly sized while loop

    So I ended up writing my code looking like this (see screenshot attached) and I want to add the upper right part into the while loop on the left.
    Is there a way to just make an awkwardly shaped while loop (which in this case would look like a lowercase R)?
    Thanks
    Solved!
    Go to Solution.
    Attachments:
    Censored.PNG ‏28 KB

    No and if NI implemented as much they would probably have to file for a new patent since the old one mentions its shape (I think).
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

  • Can't write to instrument in while loop.

    in  my case, I use 2 while loop for the progarm. one is to write the data to the instrument, another one is use local variable to change the data depend on time. the problem is the data which need write to the instrument does change. but another while loop doesn't write it to the instrument unless I push highlight excution in the diagram or choose save as in the file. could anybody help me to find the problem?

    Hi Akuma,
    the fact that it works when you highlight execution implies (perhaps) a race condition. The lightbulb serializes the execution of your VI, so that functions execute in succession although they don't depend on each other. When you then run the VI in realtime, some functions are executed at the same time, e.g. "VISA flush buffer" and "VISA write". It is important to define the order the VIs execute on your VISA interface for instance by wiring the error-cluster.
    If this doesn't help, then post your VI (or a simplified version) or a screenshot of the diagram.
    Greets, Dave
    Greets, Dave

Maybe you are looking for

  • A Portrait of an Creative Labs as a Young

    Hi-o. I'm posting this thread to spark discussion and user-interaction (supposedly the purpose of this "support" forum) My first mp3 player was an Intel 28 meg pocketconcert from, oh, I guess it was the year 2000. Amazing player, never broke, never h

  • Software not supported? what?

    Hello! This is my first time posting on here so please bare with me! I just bought myself a new Macintosh OSX computer, as to which I am very unfamiliar with. I know and have used Microsoft Windows in the past, but this is confusing me... I purchased

  • WiSM's Code 4.2.61.0

    Hi all and Happy New Year! In my effort to kick the new year off right, I have decided to upgrade my WiSM's. I really want to have 16 VLAN capability with my wireless network and so I am wanting to know if anyone has gone to the 4.2.61.0 code and if

  • How to access View Accessor in VOImpl

    Hi In our application we have two View Objects say VO1 and VO2 Now VO1 has a view accessor as VO2. VO1 is a View object with programmatically populated rows that i want to populate by executing VO2 in VOimpl of VO1. How can i access VO2 in VO1.impl f

  • DVD freezes after a while (Encore DVD 2.0)

    Hi, after burning a project with menus and several chapters, I play the DVD on a DVD player(not a computer !), and the DVD is hanging after a few chapters. My DVD burner itself seems to be ok. I tried with an other burner, and I've got the same probl