Click here to Skip to main content
14,131,177 members
Rate this:
Please Sign up or sign in to vote.
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.
Updated 23-Aug-18 21:07pm

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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.

socket client_socket = server_socket.accept();
// ...

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[^].
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)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Cookies | Terms of Service
Web02 | 2.8.190518.1 | Last Updated 24 Aug 2018
Copyright © CodeProject, 1999-2019
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100