kubisma1
kubisma1

Reputation: 317

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.

Upvotes: 0

Views: 393

Answers (2)

Paul Medcraft
Paul Medcraft

Reputation: 1406

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"

Upvotes: 1

diningphil
diningphil

Reputation: 446

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.

Upvotes: 0

Related Questions