-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathChatClient.java
91 lines (79 loc) · 1.96 KB
/
ChatClient.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import java.net.*;
import java.io.*;
public class ChatClient implements Runnable{
private Socket socket = null;
private Thread thread = null;
private DataInputStream console = null;
private DataOutputStream streamOut = null;
private ChatClientThread client = null;
public ChatClient(String serverName, int serverPort){
System.out.println("Estableciendo conexion. Espere ... ...");
try{
socket = new Socket(serverName, serverPort);
System.out.println("Conectado. " + socket);
start();
}
catch(UnknownHostException uhe){
System.out.println("Host desconocido: " + uhe.getMessage());
}
catch(IOException ioe){
System.out.println("Excepcion: " + ioe.getMessage());
}
}
public void run(){
while(thread!=null){
try{
streamOut.writeUTF(console.readLine());
streamOut.flush();
}
catch(IOException ioe){
System.out.println("error: " + ioe.getMessage());
}
}
}
public void handle(String msg){
if(msg.equals(".hasta luego")){
System.out.println("Adios. Pulsa ENTER para salir ... ... ...");
stop();
}
else{
System.out.println(msg);
}
}
public void start() throws IOException{
console = new DataInputStream(System.in);
streamOut = new DataOutputStream(socket.getOutputStream());
if(thread == null){
client = new ChatClientThread(this, socket);
thread = new Thread(this);
thread.start();
}
}
public void stop(){
if(thread != null){
thread.stop();
thread = null;
}
try{
if(console != null)
console.close();
if(streamOut != null)
streamOut.close();
if(socket != null)
socket.close();
}
catch(IOException ioe){
System.out.println("Error ...");
}
client.close();
client.stop();
}
public static void main(String args[]){
ChatClient client = null;
if(args.length != 2)
System.out.println("Uso: java ChatClient host(ej: localhost) port (usado en ClientServer)");
else{
client = new ChatClient(args[0], Integer.parseInt(args[1]));
}
}
}