Skip to content

Instantly share code, notes, and snippets.

@joffilyfe
Last active June 6, 2017 13:17
Show Gist options
  • Save joffilyfe/13dba8b238ad2c8e6fdd86082e6e7b4e to your computer and use it in GitHub Desktop.
Save joffilyfe/13dba8b238ad2c8e6fdd86082e6e7b4e to your computer and use it in GitHub Desktop.
package Chat;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
public class Client extends Thread {
private String ip;
private int port;
private Socket socket;
private String nome;
public Client(String ip, int port, String nome) {
this.ip = ip;
this.port = port;
this.nome = nome;
try {
this.socket = new Socket(ip, port);
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
try {
DataInputStream in = new DataInputStream(this.socket.getInputStream());
DataOutputStream out = new DataOutputStream(this.socket.getOutputStream());
// Enquanto estiver conectado
while(this.socket.isConnected()) {
System.out.println(String.format("[%s] Envie uma msg: ", this.nome));
Scanner teclado = new Scanner(System.in);
// Enviando mensagem
out.writeUTF(String.format("[%s]: %s", this.nome, teclado.nextLine()));
}
} catch (IOException e) {}
}
public Socket getSocket() {
return this.socket;
}
public static void main(String[] args) throws IOException {
Client cliente1 = new Client("localhost", 7171, "Joffily");
cliente1.start();
Socket socket = cliente1.getSocket();
while(socket.isConnected()) {
// Recebendo uma mensagem
DataInputStream in = new DataInputStream(socket.getInputStream());
System.out.println(in.readUTF());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment