简体   繁体   中英

Java Limited connections to server

I'm new to java and especially to java networking, but what I'm trying to do is set up a server (for a game). When TWO clients are connected to the server, I want to refuse any other connection. Am I able to close the ServerSocket? And if the ServerSocked is closed, those two connections which has been ran as threads and stored in a collection are still alive and able to cummunicate with the server? I hope you've got my point.

Here's the source code:

//Server
public synchronized List<ClientThread> getClients(){
    return clients;
}


public void run() {
    try {
        while(true){

            Socket clsock = srvsock.accept();

            if(getClients().size() == 2){
                System.out.println("Too many connections!");
                clsock.close();
                continue;
            }

            ClientThread clt = new ClientThread(clsock);
            clients.add(clt);
            clt.start();
            System.out.println("Connection accepted.");

        }
    } catch (IOException ex) {
        ex.printStackTrace(System.err);
    }
}

And with this code, I'm not able to detect on the Client if the connection is still alive, or the server has closed the connection. Thanks in advance.

Code for test client:

Socket s = new Socket("localhost", 8932);               
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));

for (int i=0; i<20; i++) {
    bw.write(String.valueOf(i));
    bw.newLine();
    bw.flush();
    Thread.sleep(1000);
}
bw.close();

And for the ClientThread:

BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
while (true) {
    String misc = in.readLine();
    System.out.println(misc);
    if (misc==null || misc.length()==0)
        break;
}
in.close();

Output:

Connection accepted.
0
Connection accepted.
0
1
Too many connections!
1
2
2
3

So it works as you intended. By the way, it is usually better to implement Runnable rather than extend Thread - see "implements Runnable" vs. "extends Thread"

Every time a connection is established, the server returns a new socket ( when you use srvsock.accept() ) for the next connection. So you can close "srvsock" without affecting "clsock". To test if they are alive, check this post How do I check if a Socket is currently connected in Java? . Hope you can solve your problem.

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