Created
June 20, 2014 23:49
-
-
Save alexandreaquiles/ad3d7287e059fb463981 to your computer and use it in GitHub Desktop.
Pequeno chat feito em Java usando Sockets. Parte do apêndice do FJ-11: http://www.caelum.com.br/apostila-java-orientacao-objetos/apendice-sockets/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package sockets.chat.cliente; | |
import java.io.IOException; | |
import java.io.PrintStream; | |
import java.net.Socket; | |
import java.net.UnknownHostException; | |
import java.util.Scanner; | |
public class Cliente { | |
private String host; | |
private int porta; | |
public Cliente(String host, int porta) { | |
this.host = host; | |
this.porta = porta; | |
} | |
public void executa() throws UnknownHostException, IOException { | |
try(Socket cliente = new Socket(this.host, this.porta); | |
Scanner teclado = new Scanner(System.in); | |
PrintStream saida = new PrintStream(cliente.getOutputStream())) { | |
System.out.println("O cliente se conectou ao servidor!"); | |
RecebedorDeMensagemDoServidor r = new RecebedorDeMensagemDoServidor(cliente.getInputStream()); | |
new Thread(r).start(); | |
while (teclado.hasNextLine()) { | |
saida.println(teclado.nextLine()); | |
} | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package sockets.chat.cliente; | |
import java.io.InputStream; | |
import java.util.Scanner; | |
class RecebedorDeMensagemDoServidor implements Runnable { | |
private InputStream servidor; | |
public RecebedorDeMensagemDoServidor(InputStream servidor) { | |
this.servidor = servidor; | |
} | |
public void run() { | |
try(Scanner s = new Scanner(this.servidor)){ | |
while (s.hasNextLine()) { | |
System.out.println(s.nextLine()); | |
} | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package sockets.chat.cliente; | |
import java.io.IOException; | |
import java.net.UnknownHostException; | |
public class RodaCliente { | |
public static void main(String[] args) | |
throws UnknownHostException, IOException { | |
new Cliente("127.0.0.1", 12345).executa(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package sockets.chat.servidor; | |
import java.io.IOException; | |
public class RodaServidor { | |
public static void main(String[] args) | |
throws IOException { | |
new Servidor(12345).executa(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package sockets.chat.servidor; | |
import java.io.IOException; | |
import java.io.PrintStream; | |
import java.net.ServerSocket; | |
import java.net.Socket; | |
import java.util.ArrayList; | |
import java.util.List; | |
public class Servidor { | |
private int porta; | |
private List<Socket> clientes; | |
public Servidor(int porta) { | |
this.porta = porta; | |
this.clientes = new ArrayList<>(); | |
} | |
public void executa() throws IOException { | |
try(ServerSocket servidor = new ServerSocket(this.porta)){ | |
System.out.println("Porta 12345 aberta!"); | |
while (true) { | |
Socket cliente = servidor.accept(); | |
System.out.println("Nova conexão com o cliente " + | |
cliente.getInetAddress().getHostAddress()); | |
this.clientes.add(cliente); | |
TratadorDeMensagemDoCliente tc = new TratadorDeMensagemDoCliente(cliente, this); | |
new Thread(tc).start(); | |
} | |
} | |
} | |
public void distribuiMensagem(Socket clienteQueEnviou, String msg) { | |
for (Socket cliente : this.clientes) { | |
if(!cliente.equals(clienteQueEnviou)){ | |
try { | |
PrintStream ps = new PrintStream(cliente.getOutputStream()); | |
ps.println(msg); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package sockets.chat.servidor; | |
import java.io.IOException; | |
import java.net.Socket; | |
import java.util.Scanner; | |
class TratadorDeMensagemDoCliente implements Runnable { | |
private Socket cliente; | |
private Servidor servidor; | |
public TratadorDeMensagemDoCliente(Socket cliente, Servidor servidor) { | |
this.cliente = cliente; | |
this.servidor = servidor; | |
} | |
public void run() { | |
try(Scanner s = new Scanner(this.cliente.getInputStream())) { | |
while (s.hasNextLine()) { | |
servidor.distribuiMensagem(this.cliente, s.nextLine()); | |
} | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Executei, mas não manda mensagem
tu tem que muda o ip que ta la , e coloca IP da sua máquina
Não envia as mensagens
Onde você fecha as conexões ?
Opa, só recebi notificação agora, alguns anos depois... hehe
O código usa try-with-resources, com as conexões dentro da expressão do try
.
Referência: https://www.baeldung.com/java-try-with-resources
Não envia as mensagens
Opa, @leonardo-fabricio.
Tenta ver se a dica do @SrSousa011 funciona pra você!
https://gist.github.com/alexandreaquiles/ad3d7287e059fb463981#gistcomment-3070149
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Onde você fecha as conexões ?