-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEnhancedChatServer.java
More file actions
194 lines (170 loc) · 6.41 KB
/
Copy pathEnhancedChatServer.java
File metadata and controls
194 lines (170 loc) · 6.41 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
package mo_phong_zalo2;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.*;
public class EnhancedChatServer extends JFrame {
private ServerSocket serverSocket;
private ExecutorService pool;
private final Set<ClientHandler> clients = ConcurrentHashMap.newKeySet();
private JTextArea logArea;
private JButton startBtn, stopBtn;
public EnhancedChatServer() {
setTitle("🔌 Zalo Server");
setSize(500, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());
logArea = new JTextArea();
logArea.setEditable(false);
add(new JScrollPane(logArea), BorderLayout.CENTER);
JPanel controlPanel = new JPanel();
startBtn = new JButton("Start Server");
stopBtn = new JButton("Stop Server");
stopBtn.setEnabled(false);
controlPanel.add(startBtn);
controlPanel.add(stopBtn);
add(controlPanel, BorderLayout.SOUTH);
startBtn.addActionListener(e -> startServer());
stopBtn.addActionListener(e -> stopServer());
setVisible(true);
}
private void startServer() {
try {
serverSocket = new ServerSocket(8888);
pool = Executors.newCachedThreadPool();
log("✅ Server started on port 8888");
startBtn.setEnabled(false);
stopBtn.setEnabled(true);
pool.execute(() -> {
while (!serverSocket.isClosed()) {
try {
Socket client = serverSocket.accept();
ClientHandler handler = new ClientHandler(client);
clients.add(handler);
pool.execute(handler);
log("🟢 Client connected: " + client);
} catch (IOException e) {
log("❌ Server stopped.");
break;
}
}
});
} catch (IOException ex) {
log("❌ Error starting server: " + ex.getMessage());
}
}
private void stopServer() {
try {
for (ClientHandler ch : clients) ch.close();
if (serverSocket != null && !serverSocket.isClosed()) {
serverSocket.close();
}
if (pool != null && !pool.isShutdown()) {
pool.shutdownNow();
}
log("🛑 Server stopped.");
startBtn.setEnabled(true);
stopBtn.setEnabled(false);
} catch (IOException ex) {
log("⚠ Error stopping server: " + ex.getMessage());
}
}
private void log(String msg) {
SwingUtilities.invokeLater(() -> logArea.append(msg + "\n"));
}
class ClientHandler implements Runnable {
private final Socket socket;
private final DataInputStream in;
private final DataOutputStream out;
private final String username;
public ClientHandler(Socket socket) throws IOException {
this.socket = socket;
this.in = new DataInputStream(socket.getInputStream());
this.out = new DataOutputStream(socket.getOutputStream());
this.username = in.readUTF();
broadcast("TEXT", AESUtil.encrypt(username + " has joined the chat."));
}
public void run() {
try {
while (true) {
String type = in.readUTF();
switch (type) {
case "TEXT":
String encryptedMsg = in.readUTF();
broadcast("TEXT", encryptedMsg);
break;
case "FILE":
case "IMAGE":
receiveAndBroadcastFile(type);
break;
case "VANISH":
String msg = in.readUTF();
int seconds = in.readInt();
broadcastVanish(msg, seconds);
break;
case "AUDIO":
receiveAndBroadcastFile(type);
break;
}
}
} catch (IOException e) {
log("🔴 Disconnected: " + username);
} finally {
clients.remove(this);
broadcast("TEXT", AESUtil.encrypt(username + " has left the chat."));
try {
socket.close();
} catch (IOException ignored) {}
}
}
private void receiveAndBroadcastFile(String type) throws IOException {
String fileName = in.readUTF();
String sender = in.readUTF();
long size = in.readLong();
byte[] buffer = new byte[(int) size];
in.readFully(buffer);
for (ClientHandler client : clients) {
if (client != this) {
client.sendFile(type, fileName, sender, buffer);
}
}
}
private void sendFile(String type, String fileName, String sender, byte[] data) throws IOException {
out.writeUTF(type);
out.writeUTF(fileName);
out.writeUTF(sender);
out.writeLong(data.length);
out.write(data);
}
public void close() throws IOException {
socket.close();
}
private void broadcast(String type, String data) {
for (ClientHandler client : clients) {
try {
client.out.writeUTF(type);
client.out.writeUTF(data);
} catch (IOException e) {
log("Error sending to " + client.username);
}
}
}
}
private void broadcastVanish(String encryptedMsg, int seconds) {
for (ClientHandler client : clients) {
try {
client.out.writeUTF("VANISH");
client.out.writeUTF(encryptedMsg);
client.out.writeInt(seconds);
} catch (IOException e) {
log("Lỗi gửi VANISH tới " + client.username);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(EnhancedChatServer::new);
}
}