How to get information from a TCP server and send to the java client

Asked

Viewed 43 times

0

The idea is this:I have a TCP server that calculates the amount of water in a water tank,when it is 250 liters should warn the client that it needs to refill. But whoever has the information that the water is running out is the server. How can I pass on the information so that the customer knows that it is necessary to fill up with water?

My method performs.

public void executa() throws IOException  {

        ServerSocket servidor = new ServerSocket(this.porta);

        System.out.println("Porta 12345 aberta!");

        for (int i = 0; i < 10; i++) {//imprime sequência de 10 números inteiros aleatórios
            quant=quant - gerador.nextInt(400);//quant=15000
            System.out.println("aqui mostra a quantidade : "+quant);
            if(quant<=250){
                System.out.println("quantidade de agua a baixo,encha de agua ");
                i=10;
            }
        }

        while (true) {
            // aceita um cliente
            Socket cliente = servidor.accept();
            System.out.println("Nova conexão com o cliente "+ cliente.getInetAddress().getHostAddress());
            // adiciona saida do cliente a lista
            PrintStream ps = new PrintStream(cliente.getOutputStream());
            this.clientes.add(ps);

            // cria tratador de cliente numa nova thread
            TrataCliente tc = new TrataCliente(cliente.getInputStream(), this);
            new Thread(tc).start();

        }
} 

1 answer

1

You can use the ConcurretHashMap to store the list of connected clients

ConcurrentHashMap<String, Socket> clientesAtivos = new ConcurrentHashMap<String, Socket>();

clientesAtivos.put(clientsocket.getInetAddress().getHostAddress(), clientsocket);

When the box is 250 liters, go through the list of customers and send the message warning.

for(String clientHost : clientesAtivos.keySet()) {
      // obtenha cada socket e envie a mensagem
}

Reference

Browser other questions tagged

You are not signed in. Login or sign up in order to post.