A new connection is established when the
accept()
method called for the listening socket returns. The connection is closed when closing the socket returned by the
accept()
call. So you have to change the counter at those points in your code.
Basically:
socket client_socket = server_socket.accept();
conn_counter++;
client_socket.close();
conn_counter--;
If a server has to support multiple clients connected at the same time, it has to use an own thread for each connection. Such is handled by most socket tutorials like
Introducing Threads in Socket Programming in Java - GeeksforGeeks[
^].