-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServerThread.java
More file actions
100 lines (85 loc) · 3.08 KB
/
ServerThread.java
File metadata and controls
100 lines (85 loc) · 3.08 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package server.domain;
import server.utils.DecryptionUtils;
import server.view.ServerGUI;
import javax.security.sasl.AuthenticationException;
import java.io.*;
import java.net.Socket;
import java.util.Vector;
import static server.utils.ErrorMessage.STRING_INVALID_PASSWORD;
import static server.utils.OutputMessage.*;
class ServerThread implements Runnable {
static Vector<PrintWriter> list = new Vector<>();
private Socket socket;
private PrintWriter writer;
private ServerGUI serverGUI;
private ServerInfo serverInfo;
public ServerThread(Socket socket, ServerGUI serverGUI, ServerInfo serverInfo) {
this.socket = socket;
this.serverGUI = serverGUI;
this.serverInfo = serverInfo;
PrintWriter tempWriter = null;
try {
tempWriter = new PrintWriter(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
writer = tempWriter;
list.add(writer);
}
@Override
public void run() {
String name = null;
String password;
try (InputStream inputStream = socket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(inputStreamReader)) {
name = reader.readLine();
password = reader.readLine();
validatePassword(name, password);
sendAll("#" + name + STRING_LOGIN_MESSAGE.getMessage());
addUser(name);
while (true) {
String message = reader.readLine();
if (message == null)
break;
sendAll("[" + name + "]" + message);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
list.remove(writer);
sendAll("#" + name + STRING_LOGOUT_MESSAGE.getMessage());
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
void validatePassword(String name, String password) throws AuthenticationException {
try {
String encryptedPassword = DecryptionUtils.decrypt(password, serverInfo.getKey());
if (!encryptedPassword.equals(serverInfo.getPassword())) {
sendAll("#" + name + STRING_LOGIN_ERROR_MESSAGE.getMessage());
throw new AuthenticationException(STRING_INVALID_PASSWORD.getMessage());
}
} catch (Exception e) {
e.printStackTrace();
throw new AuthenticationException("Password validation failed.");
}
}
private void sendAll(String message) {
serverGUI.chatList(message + "\n");
for (PrintWriter writer : list) {
writer.println(message);
writer.flush();
}
}
private void addUser(String name) {
serverGUI.updateUserList(name);
}
/*public Document toXmlDocument() {
// Implement this method to convert ServerThread state to XML if needed
return null;
}*/
}