Question

I'm new in Networking and I'm trying to make a small java application for chatting. What I want is the ServerSocket to accept one and only one connection.If a second Socket tries to connect to the ServerSocket it will throw an exception so the user who launched the socket knows that he can't connect to that ServerSocket I looked at the javadoc and I've found that constructor.

public ServerSocket(int port, int backlog) throws IOException

Creates a server socket and binds it to the specified local port number, with the specified backlog. A port number of 0 means that the port number is automatically allocated, typically from an ephemeral port range. This port number can then be retrieved by calling getLocalPort.

and I tried this

class Service implements Runnable {
    private Socket maChaussette;

    Service(Socket s) {
        maChaussette = s;
    }

    public void run() {
        System.out.println("connection established");
        while (true) {
            System.out.print("");
        }
        //maChaussette.close();
    }
}

Server :

class Serv {
    public static void main(String[] a) throws IOException {
        ServerSocket socketAttente;
        socketAttente = new ServerSocket(11111, 1);
        boolean conn = false;
        Thread t;
        while (true) {
            Socket s = socketAttente.accept();
            t = new Thread(new Service(s));
            t.start();
        }
        //socketAttente.close();
    }
}

client

public class Cll {
    public static final int PORT = 11111;

    public static void main(String[] arguments) {
        try {
            Socket service = new Socket("localhost", PORT);
            while (true) {
                System.out.print("");
            }
        } catch (Exception e) {
            System.err.println("Error");
            e.printStackTrace();
            System.exit(1);
        }
    }
}

I don't try to communicate or something, I just made these classes to try to block the number of connections to the ServerSocket.

But with that code if I run two Cll program I got two times the message "connection established ".

does Anybody have an idea about how to proceed to limit connections on a ServerSocket ?

Was it helpful?

Solution

Just close the ServerSocket after you accept one connection. And get rid of the 'while (true)' around the accept loop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top