-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathChatSystemServer.java
106 lines (76 loc) · 2.81 KB
/
ChatSystemServer.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
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class ChatSystemServer {
public static void main(String[] args) throws IOException, InterruptedException {
InetAddress address = InetAddress.getByName("localhost");
ServerSocket server = new ServerSocket(3000,3, address);
while(true) {
Socket newClient = server.accept();
ChatServerWorker serverWorker = new ChatServerWorker(newClient);
serverWorker.start();
}
}
}
class ChatServerWorker extends Thread {
private Socket clientSocket;
public ChatServerWorker(Socket clientSocket) {
this.clientSocket = clientSocket;
}
@Override
public void run() {
try {
startWorker();
} catch (IOException e) {
e.printStackTrace();
}
}
void startWorker() throws IOException {
// Getting the input/output streams of the client
BufferedReader clientInput = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter clientOutput = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
// Getting the keyboard input stream
BufferedReader keyboardInput = new BufferedReader(new InputStreamReader(System.in));
Thread messagePrinter = new Thread(new Runnable() {
@Override
public void run() {
while(true) {
if(clientSocket.isClosed()) {
Thread.interrupted();
break;
}
try {
if(clientInput == null) {
break;
}
String messageFromTheClient = clientInput.readLine();
if(messageFromTheClient != null) {
System.out.println("Message from the client: " + messageFromTheClient);
}
if(messageFromTheClient.equals("exit")) {
clientSocket.close();
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
// Starting the message printer on a new Thread
messagePrinter.start();
while(true) {
if(clientSocket.isClosed()) {
break;
}
String messageBack = keyboardInput.readLine();
if(messageBack.equals("exit")) {
Thread.interrupted();
}
clientOutput.println(messageBack);
clientOutput.flush();
}
clientSocket.close();
}
}