-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
336 lines (289 loc) · 10.2 KB
/
Copy pathmain.cpp
File metadata and controls
336 lines (289 loc) · 10.2 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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netdb.h>
#include <cstring>
#include <thread>
#include <ctime>
#include <vector>
#include <mutex>
#include <algorithm>
#include <fstream>
#include <sstream>
using namespace std;
// Store connected clients
struct Client {
int socket;
string name;
};
vector<Client> clients;
mutex clientsMutex;
// Print with timestamp
void printMessage(const string& sender, const string& msg) {
time_t now = time(0);
char timestamp[9];
strftime(timestamp, sizeof(timestamp), "%H:%M:%S", localtime(&now));
cout << "\033[90m[" << timestamp << "]\033[0m ";
cout << "\033[35m" << sender << ":\033[0m ";
cout << msg << endl;
}
void printSystem(const string& msg) {
cout << "\033[33m[System] " << msg << "\033[0m" << endl;
}
// Find client socket by name
int findClientSocket(const string& name) {
lock_guard<mutex> lock(clientsMutex);
for (const Client& client : clients) {
if (client.name == name) {
return client.socket;
}
}
return -1;
}
// Get list of client names
string getClientList() {
lock_guard<mutex> lock(clientsMutex);
string list;
for (const Client& client : clients) {
if (!list.empty()) list += ", ";
list += client.name;
}
return list;
}
// Send message to ALL clients except the sender
void broadcastMessage(const string& message, int senderSocket) {
lock_guard<mutex> lock(clientsMutex);
for (const Client& client : clients) {
if (client.socket != senderSocket) {
send(client.socket, message.c_str(), message.length(), 0);
}
}
}
// Send message to ALL clients
void broadcastToAll(const string& message) {
lock_guard<mutex> lock(clientsMutex);
for (const Client& client : clients) {
send(client.socket, message.c_str(), message.length(), 0);
}
}
// Send to specific client
bool sendToClient(const string& name, const string& message) {
int sock = findClientSocket(name);
if (sock != -1) {
send(sock, message.c_str(), message.length(), 0);
return true;
}
return false;
}
// Send raw bytes to specific client (for files)
bool sendBytesToClient(const string& name, const char* data, size_t length) {
int sock = findClientSocket(name);
if (sock != -1) {
send(sock, data, length, 0);
return true;
}
return false;
}
// Send raw bytes to all except sender
void broadcastBytes(const char* data, size_t length, int senderSocket) {
lock_guard<mutex> lock(clientsMutex);
for (const Client& client : clients) {
if (client.socket != senderSocket) {
send(client.socket, data, length, 0);
}
}
}
string getClientName(int socket) {
lock_guard<mutex> lock(clientsMutex);
for (const Client& client : clients) {
if (client.socket == socket) {
return client.name;
}
}
return "Unknown";
}
void removeClient(int socket) {
lock_guard<mutex> lock(clientsMutex);
clients.erase(
remove_if(clients.begin(), clients.end(),
[socket](const Client& c) { return c.socket == socket; }),
clients.end()
);
}
// Handle a single client
void handleClient(int clientSocket) {
char buf[65536]; // Larger buffer for files
// Get username
memset(buf, 0, sizeof(buf));
int bytesReceived = recv(clientSocket, buf, sizeof(buf), 0);
if (bytesReceived <= 0) {
close(clientSocket);
return;
}
string clientName = buf;
// Add to clients list
{
lock_guard<mutex> lock(clientsMutex);
clients.push_back({clientSocket, clientName});
}
printSystem("'" + clientName + "' joined the chat!");
broadcastMessage("[" + clientName + " joined the chat]", clientSocket);
// Handle messages
while (true) {
memset(buf, 0, sizeof(buf));
bytesReceived = recv(clientSocket, buf, sizeof(buf), 0);
if (bytesReceived <= 0) {
printSystem("'" + clientName + "' disconnected.");
broadcastMessage("[" + clientName + " left the chat]", clientSocket);
break;
}
string message(buf, bytesReceived);
// Check for special commands
if (message.rfind("FILE:", 0) == 0) {
// File transfer: FILE:recipient:filename:filesize:data
// Parse header
size_t pos1 = message.find(':', 5); // After "FILE:"
size_t pos2 = message.find(':', pos1 + 1);
size_t pos3 = message.find(':', pos2 + 1);
if (pos1 != string::npos && pos2 != string::npos && pos3 != string::npos) {
string recipient = message.substr(5, pos1 - 5);
string filename = message.substr(pos1 + 1, pos2 - pos1 - 1);
string sizeStr = message.substr(pos2 + 1, pos3 - pos2 - 1);
size_t fileSize = stoul(sizeStr);
printSystem(clientName + " is sending file '" + filename + "' (" + sizeStr + " bytes) to " + recipient);
// Rebuild message with sender info
string header = "FILE:" + clientName + ":" + filename + ":" + sizeStr + ":";
string fileData = message.substr(pos3 + 1);
string fullMessage = header + fileData;
if (recipient == "all") {
broadcastBytes(fullMessage.c_str(), fullMessage.length(), clientSocket);
} else {
if (!sendBytesToClient(recipient, fullMessage.c_str(), fullMessage.length())) {
string error = "[System] User '" + recipient + "' not found.";
send(clientSocket, error.c_str(), error.length(), 0);
}
}
}
}
else if (message.rfind("USERS", 0) == 0) {
// User list request
string list = "[Online users: " + getClientList() + "]";
send(clientSocket, list.c_str(), list.length(), 0);
}
else if (message.rfind("MSG:", 0) == 0) {
// Private message: MSG:recipient:message
size_t pos1 = message.find(':', 4);
if (pos1 != string::npos) {
string recipient = message.substr(4, pos1 - 4);
string privateMsg = message.substr(pos1 + 1);
string formatted = "[PM from " + clientName + "]: " + privateMsg;
if (!sendToClient(recipient, formatted)) {
string error = "[System] User '" + recipient + "' not found.";
send(clientSocket, error.c_str(), error.length(), 0);
} else {
printSystem(clientName + " -> " + recipient + ": " + privateMsg);
}
}
}
else {
// Regular message
printMessage(clientName, message);
string fullMessage = clientName + ": " + message;
broadcastMessage(fullMessage, clientSocket);
}
}
removeClient(clientSocket);
close(clientSocket);
}
// Server input thread
void serverInput() {
char buf[4096];
while (true) {
cin.getline(buf, sizeof(buf));
if (strlen(buf) == 0) continue;
string input = buf;
if (input == "/quit" || input == "/q") {
printSystem("Shutting down server...");
exit(0);
}
else if (input == "/help" || input == "/h") {
cout << "\n\033[33m========== SERVER COMMANDS ==========\033[0m\n";
cout << " /help, /h Show this help\n";
cout << " /quit, /q Shutdown server\n";
cout << " /list, /l List connected clients\n";
cout << " /broadcast <msg> Send to all clients\n";
cout << "\033[33m=====================================\033[0m\n\n";
}
else if (input == "/list" || input == "/l") {
lock_guard<mutex> lock(clientsMutex);
cout << "\n\033[33mConnected clients (" << clients.size() << "):\033[0m\n";
for (const Client& c : clients) {
cout << " - " << c.name << "\n";
}
cout << "\n";
}
else if (input.rfind("/broadcast ", 0) == 0 || input.rfind("/b ", 0) == 0) {
size_t spacePos = input.find(' ');
string message = "[Server]: " + input.substr(spacePos + 1);
broadcastToAll(message);
printSystem("Broadcasted: " + input.substr(spacePos + 1));
}
else {
string message = "[Server]: " + input;
broadcastToAll(message);
printMessage("You (to all)", input);
}
}
}
int main() {
cout << "\033[2J\033[H";
cout << "\033[35m";
cout << "================================\n";
cout << " MULTI-CLIENT SERVER v4.0 \n";
cout << " (with file transfer) \n";
cout << "================================\n";
cout << "\033[0m\n";
int listening = socket(AF_INET, SOCK_STREAM, 0);
if (listening == -1) {
cerr << "Can't create a socket!" << endl;
return 1;
}
int opt = 1;
setsockopt(listening, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(54000);
hint.sin_addr.s_addr = INADDR_ANY;
memset(&hint.sin_zero, 0, 8);
if (::bind(listening, (struct sockaddr*)&hint, sizeof(hint)) == -1) {
cerr << "Bind failed!" << endl;
return 1;
}
if (listen(listening, SOMAXCONN) == -1) {
cerr << "Listen failed!" << endl;
return 1;
}
printSystem("Server started on port 54000");
printSystem("Type /help for commands.\n");
thread inputThread(serverInput);
inputThread.detach();
while (true) {
sockaddr_in client;
socklen_t clientSize = sizeof(client);
int clientSocket = accept(listening, (struct sockaddr*)&client, &clientSize);
if (clientSocket == -1) {
cerr << "Accept failed!" << endl;
continue;
}
char host[NI_MAXHOST];
inet_ntop(AF_INET, &client.sin_addr, host, NI_MAXHOST);
printSystem(string("New connection from ") + host);
thread t(handleClient, clientSocket);
t.detach();
}
close(listening);
return 0;
}