user7237460
user7237460

Reputation:

Why isn't my break not going back to my label?

So for school I am trying to make an Asynchronous chat program with 2 classes; the server and the client. Basically the client connects to the server, and writes text until the string or are entered. If is entered then the client listens for text and the server gets to send instead. If is entered the client disconnects, and the server resets the connections and waits for client to connect again. I am trying to solve these requirements with some do..whiles, and then a continue label to reset the connections. Right now if the client sends the connection resets but the server just stops the build instead of returning to my startConnections label. Here is my code for my server which I am using the break in:

 public static void main(String args[]) {

    startConnections:
    {
        System.out.println("RESET TEST");

        try {
            server = new ServerSocket(12345, 100);


            System.out.println("Waiting for client");
            connection = server.accept();
            System.out.println("Client Connected");

            output = new ObjectOutputStream(connection.getOutputStream());

            output.flush();

            input = new ObjectInputStream(connection.getInputStream());

            do {

                do {
                    messageIn = (String) input.readObject();

                    System.out.println("CLIENT SAYS: " + messageIn);
                } while ((!messageIn.equals("<OVER>")) & (!messageIn.equals("<OUT>")));
                if (messageIn.equals("<OUT>")) {
                    break startConnections;
                }

                do {
                    System.out.print("RESPONSE: ");

                    keyboardInput = new Scanner(System.in);
                    messageOut = keyboardInput.nextLine();

                    output.writeObject(messageOut);

                } while (!messageOut.equals("<OVER>"));

            } while (!messageOut.equals("<OUT>"));

        } catch (Exception e) {
            System.out.println("Oops SERVER! : " + e.toString());
        }

    }
}

Upvotes: 0

Views: 40

Answers (1)

Sentry
Sentry

Reputation: 4113

It works as it should

The break statement terminates the labeled statement; it does not transfer the flow of control to the label. Control flow is transferred to the statement immediately following the labeled (terminated) statement.

So the next executed statement after the break call is what comes after the loop labeled with startConnections

To get the behavior you want, you need to use continue:

continue startConnections;

A labeled continue statement skips the current iteration of an outer loop marked with the given label.

Upvotes: 1

Related Questions