-
Notifications
You must be signed in to change notification settings - Fork 0
/
ChatClient.java
108 lines (77 loc) · 2.33 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package ie.gmit.dip;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class ChatClient {
public static final int DAYTIME_PORT = 13;
public static void main(String[] args){
try {
String hostname = args.length > 0 ? args[0] : "localhost";
Socket socket = new Socket(hostname,DAYTIME_PORT);
Scanner scanner = new Scanner(System.in);
BufferedReader inputReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
OutputStreamWriter outputWriter = new OutputStreamWriter(socket.getOutputStream());
System.out.println("You are connected to server");
System.out.println("Type messages to server below (enter /q to quit)");
Runnable output = new Runnable()
{
String outputMessage;
@Override
public void run() {
while(true){
outputMessage = scanner.nextLine();
try {
outputWriter.write(outputMessage + "\r\n");
outputWriter.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
Runnable input = new Runnable() {
String inputMessage;
@Override
public void run() {
try {
inputMessage = inputReader.readLine();
while(!(inputMessage.equals("/q")))
{
System.out.println("Server : "+ inputMessage);
inputMessage = inputReader.readLine();
}
System.out.println("Server left the chat");
outputWriter.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e2) {
try {
outputWriter.close();
socket.close();
System.out.println("You have successfully left the chat");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
Thread.UncaughtExceptionHandler exceptionHandler = new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable exception) {
//ignore
}
};
Thread outputThread = new Thread(output);
Thread inputThread = new Thread(input);
outputThread.setUncaughtExceptionHandler(exceptionHandler);
inputThread.setUncaughtExceptionHandler(exceptionHandler);
outputThread.start();
inputThread .start();
}catch (IOException e){
//ignore
}
}
}