forked from jerry10004/SimpleChat
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatClient.java
More file actions
80 lines (77 loc) · 1.84 KB
/
ChatClient.java
File metadata and controls
80 lines (77 loc) · 1.84 KB
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
import java.net.*;
import java.io.*;
public class ChatClient {
public static void main(String[] args) {
if(args.length != 2){
System.out.println("Usage : java ChatClient <username> <server-ip>");
System.exit(1);
}
Socket sock = null;
BufferedReader br = null;
PrintWriter pw = null;
boolean endflag = false;
try{
sock = new Socket(args[1], 10001);
pw = new PrintWriter(new OutputStreamWriter(sock.getOutputStream()));
br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
// send username.
pw.println(args[0]);
pw.flush();
InputThread it = new InputThread(sock, br);
it.start();
String line = null;
while((line = keyboard.readLine()) != null){
pw.println(line);
pw.flush();
if(line.equals("/quit")){
endflag = true;
break;
}
}
System.out.println("Connection closed.");
}catch(Exception ex){
if(!endflag)
System.out.println(ex);
}finally{
try{
if(pw != null)
pw.close();
}catch(Exception ex){}
try{
if(br != null)
br.close();
}catch(Exception ex){}
try{
if(sock != null)
sock.close();
}catch(Exception ex){}
} // finally
} // main
} // class
class InputThread extends Thread{
private Socket sock = null;
private BufferedReader br = null;
public InputThread(Socket sock, BufferedReader br){
this.sock = sock;
this.br = br;
}
public void run(){
try{
String line = null;
while((line = br.readLine()) != null){
System.out.println(line);
}
}catch(Exception ex){
}finally{
try{
if(br != null)
br.close();
}catch(Exception ex){}
try{
if(sock != null)
sock.close();
}catch(Exception ex){}
}
} // InputThread
}