Material do Treinamento Java e Orientação a Objetos
while (s.hasNextLine()) { System.out.println(s.nextLine()); }
12 13 14
}
15 16
}
Já o Servidor sofreu bastante modificações. A classe TrataCliente é a responsável por cuidar de cada cliente conectado no sistema: 1
public class Servidor {
2 3 4 5 6
public static void main(String[] args) throws IOException { // inicia o servidor new Servidor(12345).executa(); }
7 8 9
private int porta; private List<PrintStream> clientes;
10 11 12 13 14
public Servidor (int porta) { this.porta = porta; this.clientes = new ArrayList<PrintStream>(); }
15 16 17 18
public void executa () throws IOException { ServerSocket servidor = new ServerSocket(this.porta); System.out.println("Porta 12345 aberta!");
19 20 21 22 23 24 25
while (true) { // aceita um cliente Socket cliente = servidor.accept(); System.out.println("Nova conexão com o cliente " + cliente.getInetAddress().getHostAddress() );
26
// adiciona saida do cliente à lista PrintStream ps = new PrintStream(cliente.getOutputStream()); this.clientes.add(ps);
27 28 29 30
// cria tratador de cliente numa nova thread TrataCliente tc = new TrataCliente(cliente.getInputStream(), this); new Thread(tc).start();
31 32 33 34 35
}
36
Capítulo 19 - Apêndice - Sockets - Solução do sistema de chat - Página 264