Click here to Skip to main content
15,881,812 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Simply I have a java Socket program and I want to count number of clients connected the socket, increment on new connection and decrements when connections are closed. What is the best way to achieve this ?

What I have tried:

Actually I am getting confused .I want any sample code.
Posted
Updated 23-Aug-18 21:07pm

1 solution

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:
Java
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[^].
 
Share this answer
 
Comments
FerdouZ 24-Aug-18 4:53am    
Yups I got it.
Thank you :)
Jochen Arndt 24-Aug-18 5:01am    
Fine and thank you for accepting my solution.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900