6
How do I see how many customers are connected to my ServerSocket
java?
6
How do I see how many customers are connected to my ServerSocket
java?
5
I don’t know if there is one ID per user that helps to identify who are the clients, but in the matter of TCP servers, what can always be counted is the connection made by a client and from this connection made we can obtain data and try to create an identity to be able to distinguish.
Inside the loop while
we use the ServerSocket.accept();
to determine when there was the connection, then the account would be something like:
int i = 0;
ServerSocket ss = new ServerSocket(8088);
while (true) {
Socket socket = ss.accept();
i += 1;
...
}
Since the loop is "infinite", you can use a Thread to show the i
using the System.out
for example. If you seek to count connections made at the exact moment this should help you.
But this only counts the connections made. Usually the client connects, receives the data and disconnects. If it is a web page, then every image, js, css, within the page can generate a new connection, ie a client generates several connections.
Note: Web browsers usually use the instruction
Connection: keep-alive
in the request "headers", which should do what indicates that the browser should keep the connection open for the elements on the page, but this connection will not always stay open.
We can count the number of connections made, now what we need is to give a identity for each customer.
An example of identifying the customer is using socket.getRemoteSocketAddress();
(which may not be 100% guaranteed, but this is another story) combined with a list. The code should look something like this:
List<String> clientes = new ArrayList<String>();
...
ServerSocket ss = new ServerSocket(8088);
while (true) {
Socket socket = ss.accept();
String addr = ss.getRemoteSocketAddress().toString();
if (!clientes.contains(addr)) {
clientes.add(addr);
}
}
This way we will save all connected addresses (remember in these cases it is always necessary to use a Thread, or your socket to be in a separate Thread) and to count just use clientes.size()
.
The example I gave counts the connections, but does not clear the list, so that the number will never decrease, it will only increase. In this case, if what you need is a counter in "real time", you can use a HashMap
to create a list where items expire (similar to what online counters do).
Create a HashMap
thus:
Map<String, Date> clientes = new HashMap<String, Date>();
String
will have the "address".Date
will be used to check whether data should expire.The "Server" should look like this:
Map<String, Date> clientes = new HashMap<String, Date>();
ServerSocket ss = new ServerSocket(8088);
while (true) {
Socket socket = ss.accept();
String addr = ss.getRemoteSocketAddress().toString();
// Atualiza o horário de um endereço existente ou adiciona um novo endereço.
clientes.put(addr, new Date());
}
And in another method (which must have access to the variable clientes
), you must create a check to detect if the client’s time has expired (it does not need to be a long time, 30 seconds is better than good).
First we create a HashMap
to relistar:
Map<String, Date> relista;
Then we create a loop to check what is still within the time limit:
relista = new HashMap<String, Date>(); // Limpa relista para aproveitá-la novamente.
Date agora = new Date();
agora.add(Calendar.SECOND, -30); // 30 segundos mencionado anteriormente, edite conforme necessidade.
for (String key : clientes.keySet()) {
Date timer = clientes.get(key);
if (!agora.after(timer)) {
// Se o item ainda está dentro dos 30 segundos então "mantém na lista".
relista.put(key, timer);
}
}
clientes = relista; // Atualiza a lista de clientes conectados.
The last example I mentioned is just a simple way to understand how to list, but the use of getRemoteSocketAddress
is not exact because the IP may change (both on a private network and on the internet). The most guaranteed way would be by using session, but it will require external libraries to facilitate the work (it is possible to do without, but it takes a lot of time to develop something). There are libraries that can help you, such as javax.servlet.http.HttpSession
(of course if used for HTTP).
Browser other questions tagged java socket
You are not signed in. Login or sign up in order to post.
List<String> clientes = new ArrayList<String>();
...clientes = addr;
... There’s nothing wrong here?– Gustavo Cinque
@Gustavocinque Thanks is at the time of the rush, it has been corrected.
– Guilherme Nascimento