Last active
June 6, 2017 13:17
-
-
Save joffilyfe/13dba8b238ad2c8e6fdd86082e6e7b4e to your computer and use it in GitHub Desktop.
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 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