views:

97

answers:

2

Okay, this sounds simple, but I tried all the simple things and it still doesn't work properly.

import java.net.*;
import java.io.*;

public class MyServer{
    public static void main(String[] args) throws IOException {

        int MAX_PLAYERS = 1;
        int players = 0;

        ServerSocket serverSocket = new ServerSocket(43);

        while(players < MAX_PLAYERS){
            if(players < MAX_PLAYERS)
             new MyThread().start(serverSocket.accept());

            players++;
        }



        serverSocket.close();
        System.exit(0);
    }
}
A: 

If two players connect at close to the same time this is possible. You need to exclusively lock or syncronize the section where you are accepting new players.

GrayWizardx
No, `ServerSocket.accept()` will take care of that, it blocks until a client is connected.
Bombe
I was actually talking about side effects from how the OP spawns the new thread. I think there might be a side effect there.
GrayWizardx
A: 

The problem with your code is due to bad formatting. If you connect to a client you should increment the player variable only when this happens.

    while(players < MAX_PLAYERS){
        if(players < MAX_PLAYERS)  >>{<<<
            new MyThread().start(serverSocket.accept());

            players++;
        >>}<<
    }

I'm surprised that you connected to a client in the first place.

Additionally, the start method for a thread does not take in parameters. The runnable interface doesn't take in a parameter either for the run method.

monksy
If I am understanding the code correctly this will block waiting for the first accept connection, which will return the Socket, completing the new thread spawn. At which point the player count is incremented (with side-effects as noted). So he should always get only one connection, and then bail. Since player goes from 0 => and breaks the while.
GrayWizardx
I don't see how the curly braces change anything. The if-statement checks the same condition as the while-loop and thus will always be true.
Whisty
Another answer that is clearly not the answer. My guess is that the problem description is wrong. :)
Bombe