-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.cpp
More file actions
277 lines (238 loc) · 9.08 KB
/
client.cpp
File metadata and controls
277 lines (238 loc) · 9.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
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
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
#include <thread>
#include <ctime>
#include <atomic>
#include <fstream>
#include <sstream>
#include <sys/stat.h>
using namespace std;
atomic<bool> running(true);
string username;
int globalSocket; // For file receiving
// Print message with timestamp
void printMessage(const char* sender, const char* 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[36m" << sender << ":\033[0m ";
cout << msg << endl;
}
void printSystem(const char* msg) {
cout << "\033[33m[System] " << msg << "\033[0m" << endl;
}
// Save received file
void saveFile(const string& sender, const string& filename, const string& data) {
// Create downloads folder if it doesn't exist
mkdir("downloads", 0777);
string savePath = "downloads/" + filename;
// If file exists, add number
struct stat buffer;
int count = 1;
string finalPath = savePath;
while (stat(finalPath.c_str(), &buffer) == 0) {
size_t dotPos = savePath.find_last_of('.');
if (dotPos != string::npos) {
finalPath = savePath.substr(0, dotPos) + "_" + to_string(count) + savePath.substr(dotPos);
} else {
finalPath = savePath + "_" + to_string(count);
}
count++;
}
ofstream file(finalPath, ios::binary);
if (file.is_open()) {
file.write(data.c_str(), data.length());
file.close();
cout << "\033[32m[File] Received '" << filename << "' from " << sender
<< " → saved to " << finalPath << "\033[0m" << endl;
} else {
cout << "\033[31m[Error] Could not save file: " << filename << "\033[0m" << endl;
}
}
// Receive messages from server
void receiveMessages(int socket) {
char buf[65536]; // Larger buffer for files
while (running) {
memset(buf, 0, sizeof(buf));
int bytesReceived = recv(socket, buf, sizeof(buf), 0);
if (bytesReceived == -1) {
if (running) printSystem("Connection error.");
break;
}
if (bytesReceived == 0) {
printSystem("Server disconnected.");
break;
}
string message(buf, bytesReceived);
// Check if it's a file transfer
if (message.rfind("FILE:", 0) == 0) {
// Parse: FILE:sender:filename:filesize:data
size_t pos1 = message.find(':', 5);
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 sender = message.substr(5, pos1 - 5);
string filename = message.substr(pos1 + 1, pos2 - pos1 - 1);
string fileData = message.substr(pos3 + 1);
saveFile(sender, filename, fileData);
}
} else {
// Regular message
time_t now = time(0);
char ts[9];
strftime(ts, sizeof(ts), "%H:%M:%S", localtime(&now));
cout << "\033[90m[" << ts << "]\033[0m " << message << endl;
}
}
running = false;
}
// Read file into string
bool readFile(const string& filepath, string& content) {
ifstream file(filepath, ios::binary);
if (!file.is_open()) {
return false;
}
stringstream buffer;
buffer << file.rdbuf();
content = buffer.str();
file.close();
return true;
}
// Get just the filename from path
string getFilename(const string& path) {
size_t pos = path.find_last_of("/\\");
if (pos != string::npos) {
return path.substr(pos + 1);
}
return path;
}
// Send messages to server
void sendMessages(int socket) {
char buf[4096];
while (running) {
cin.getline(buf, sizeof(buf));
if (!running) break;
if (strlen(buf) == 0) continue;
string input = buf;
// Commands
if (input[0] == '/') {
if (input == "/quit" || input == "/q") {
printSystem("Goodbye!");
running = false;
close(socket);
break;
}
else if (input == "/help" || input == "/h") {
cout << "\n\033[33m============== COMMANDS ==============\033[0m\n";
cout << " /help, /h Show this help\n";
cout << " /quit, /q Disconnect and exit\n";
cout << " /clear, /c Clear the screen\n";
cout << " /users List online users\n";
cout << " /msg <user> <message> Private message\n";
cout << " /sendfile <user> <file> Send file to user\n";
cout << " /sendfile all <file> Send file to everyone\n";
cout << " /me <action> Action message\n";
cout << "\033[33m======================================\033[0m\n\n";
}
else if (input == "/clear" || input == "/c") {
cout << "\033[2J\033[H";
printSystem("Screen cleared.");
}
else if (input == "/users") {
send(socket, "USERS", 5, 0);
}
else if (input.rfind("/msg ", 0) == 0) {
//Private message: /msg darren hello there
size_t space1 = input.find(' ', 5);
if (space1 != string::npos) {
string recipient = input.substr(5, space1 - 5);
string message = input.substr(space1 + 1);
string formatted = "MSG:" + recipient + ":" + message;
send(socket, formatted.c_str(), formatted.length(), 0);
cout << "\033[90m[PM to " << recipient << "]\033[0m " << message << endl;
} else {
printSystem("Usage: /msg <username> <message>");
}
}
else if (input.rfind("/sendfile ", 0) == 0) {
// File transfer
size_t space1 = input.find(' ', 10);
if (space1 != string::npos) {
string recipient = input.substr(10, space1 - 10);
string filepath = input.substr(space1 + 1);
string fileContent;
if (readFile(filepath, fileContent)) {
string filename = getFilename(filepath);
//Build message: FILE:recipient:filename:size:data
string header = "FILE:" + recipient + ":" + filename + ":" +
to_string(fileContent.length()) + ":";
string fullMessage = header + fileContent;
send(socket, fullMessage.c_str(), fullMessage.length(), 0);
cout << "\033[32m[File] Sending '" << filename << "' ("
<< fileContent.length() << " bytes) to " << recipient << "\033[0m" << endl;
} else {
cout << "\033[31m[Error] Could not read file: " << filepath << "\033[0m" << endl;
}
} else {
printSystem("Usage: /sendfile <username|all> <filepath>");
}
}
else if (input.rfind("/me ", 0) == 0) {
string action = "* " + username + " " + input.substr(4);
send(socket, action.c_str(), action.length(), 0);
printMessage("You", action.c_str());
}
else {
printSystem("Unknown command. Type /help for commands.");
}
}
else {
send(socket, buf, strlen(buf), 0);
printMessage("You", buf);
}
}
}
int main() {
cout << "\033[2J\033[H";
cout << "\033[36m";
cout << "================================\n";
cout << " CHAT CLIENT v4.0 \n";
cout << " (with file transfer) \n";
cout << "================================\n";
cout << "\033[0m\n";
cout << "Enter your username: ";
getline(cin, username);
if (username.empty()) username = "Anonymous";
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
cerr << "Can't create a socket! Quitting" << endl;
return 1;
}
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(54000);
inet_pton(AF_INET, "127.0.0.1", &hint.sin_addr);
printSystem("Connecting to server...");
int connectRes = connect(sock, (struct sockaddr*)&hint, sizeof(hint));
if (connectRes == -1) {
cerr << "Could not connect to server! Is it running?" << endl;
return 1;
}
globalSocket = sock;
send(sock, username.c_str(), username.length(), 0);
printSystem("Connected! Type /help for commands.\n");
thread recvThread(receiveMessages, sock);
sendMessages(sock);
running = false;
if (recvThread.joinable()) {
recvThread.join();
}
close(sock);
return 0;
}