Search code examples
javasocketsclientserverserversocket

Getting the ServerSocket to know what data to listen for


I'm working on a simple client / server login system and I'm having trouble getting my server to listen for the right data being sent by the client. On my client I have methods sendRegistrationData() and sendLoginData(), and on my server I have waitForRegistrationData() and waitForLoginData(). The code in these methods are fine and do what they're supposed to do, but my server can't seem to tell when to wait for registration or login data and either runs through both wait methods, or goes to the first one and ignores the second.

For example, I have this method;

private void waitForData() {
    setupClient();
    waitForRegistrationData();
    waitForLoginData();
}

What this done was handle the registration data, and then handle the login data even if I only sent the login data. So I thought to try and get around this, I'd write an int to the server for sendRegistrationData and sendLoginData like clientOut.writeInt(1) for sendRegistrationData and clientOut.writeInt(2) for sendLoginData, and then server-side I would do an int like below to tell the server how to distinguish between the two;

private void waitForData() {
    setupClient();
    try {
        if (serverIn.readInt() == 1)
            waitForRegistrationData();

        if (serverIn.readInt() == 2)
            waitForLoginData();
    } catch (IOException ex) {
        System.out.println(ex.getMessage());
    }
}

This worked fine last night but for some reason has stopped working and when I try to login in as soon as I start the client, it just returns null because it seems the server isn't reaching waitForLoginData because waitForRegistrationData is above it, or so I'm guessing.

How could I get my server to know whether or not to listen for registration or login data? here's an Imgur link showing my my client / server in action last night when it was working as intended. Right now when if I tried to do the "Login without register" as seen in that picture, it would cause the problems I've just said where the server just doesn't listen for login data.

Hopefully I've explained my problem enough for someone to know what I'm talking about. I found it hard to explain the problem. Thanks.


Solution

  • You should call readInt() once, and probably use the result in a switch statement. At present you're trying to consume two integers when only one has been sent.