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);
}
}
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.
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.
精彩评论