简体   繁体   中英

Limiting the number of connections to a server

I have a multi-threaded server in Java, however I want to limit the number of connected clients to 2. It's a basic application, just being used for testing.

On my server I have an int userNo attribute that assigns clients the value of either 0 or 1.

My question is, is there a better way of handling this. I only want up to 2 clients to connect, and I want my application to ignore any further requests.

Pseduo code:

    if(userNo == 0) {
    this is player 1;
    }
    if (userNo == 1) {
    this is player 2;
    }
    else {
    do nothing
    }

I would do something like this:

int connectedClientCount = 0;
// ...
while(true) {
    ServerSocket ss = ...
    Socket s = ss.accept();
    if(connectedClientCount == 2) {
        // Do stuff to tell connected Client that he is rejected because of max clients...
    } else {
        connectedClientCount++;
        // cool stuff...
    }
}

and somewhere else in you code (which gets executed on client disconnect)

public void clientDisconnected() {
    connectedClientCount--;
}

Because of sake of simplicity I don't use thread synchronization in this example..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM