Skip to content

Instantly share code, notes, and snippets.

@alexandreaquiles
Created June 20, 2014 23:49
Show Gist options
  • Save alexandreaquiles/ad3d7287e059fb463981 to your computer and use it in GitHub Desktop.
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/
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());
}
}
}
}
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());
}
}
}
}
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();
}
}
package sockets.chat.servidor;
import java.io.IOException;
public class RodaServidor {
public static void main(String[] args)
throws IOException {
new Servidor(12345).executa();
}
}
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();
}
}
}
}
}
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();
}
}
}
@ildeteID
Copy link

Como que execute isso..

@pnalvarez
Copy link

Como faço pra fazer o chat funcionar?

@ja8an
Copy link

ja8an commented Mar 3, 2018

roda o RodaServidor.java e o RodaCliente.java

@DaniloMicaias
Copy link

Executei, mas não manda mensagem

@douglasMouraBezerra
Copy link

Onde você fecha as conexões ?

@SrSousa011
Copy link

Executei, mas não manda mensagem

tu tem que muda o ip que ta la , e coloca IP da sua máquina

@leonardo-fabricio
Copy link

Não envia as mensagens

@alexandreaquiles
Copy link
Author

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

@alexandreaquiles
Copy link
Author

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