Многопользовательский чат TCP |
18.11.2024, 00:02. Показов 10079. Ответов 2
Всем привет!
Делаю код многопользовательского чата на c++ с реализацией через TCP.
Возникла проблема, а именно - Когда запущен сервер и 2 пользователя, если 1 подключенный пользователь пишет сообщение то сообщение не отправляется, сразу выскакивает данное сообщение-
Microsoft Visual C++ Runtime Library
Debug Error!
Program: E:\program\Server\x64\Debug\Server.exe
abort has been called
(Press Retry to debug the application)
Код сервера:
| C++ | 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
| #include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <algorithm>
#include <winsock2.h>
#include <thread>
#include <mutex>
#pragma comment(lib, "ws2_32.lib")
#pragma warning(disable: 4996)
using namespace std;
struct Client {
SOCKET socket;
string nickname;
};
vector<Client> clients;
mutex clientsMutex; // Глобальный мьютекс для синхронизации
const string PASSWORD = "secret";
const string HISTORY_FILE = "chat_history.txt";
void SaveMessageToHistory(const string& message) {
ofstream out(HISTORY_FILE, ios::app);
if (out.is_open()) {
out << message << endl;
}
}
void LoadHistory(vector<string>& history) {
ifstream in(HISTORY_FILE);
if (in.is_open()) {
string line;
while (getline(in, line)) {
history.push_back(line);
}
}
}
void SendHistoryToClient(SOCKET clientSocket) {
vector<string> history;
LoadHistory(history);
int start = max(0, static_cast<int>(history.size()) - 10);
for (int i = start; i < history.size(); ++i) {
string msg = history[i];
int msg_size = msg.size();
send(clientSocket, (char*)&msg_size, sizeof(int), NULL);
send(clientSocket, msg.c_str(), msg_size, NULL);
}
}
void RemoveClient(const string& nickname) {
lock_guard<mutex> lock(clientsMutex);
auto it = find_if(clients.begin(), clients.end(), [&nickname](const Client& client) {
return client.nickname == nickname;
});
if (it != clients.end()) {
closesocket(it->socket);
cout << "Client \"" << it->nickname << "\" has been removed from the chat." << endl;
clients.erase(it);
}
else {
cout << "Client with nickname \"" << nickname << "\" not found." << endl;
}
}
void ClientHandler(Client* client) {
SOCKET clientSocket = client->socket;
int msg_size;
SendHistoryToClient(clientSocket);
while (true) {
int result = recv(clientSocket, (char*)&msg_size, sizeof(int), NULL);
if (result <= 0) {
cout << "Client \"" << client->nickname << "\" disconnected.\n";
// Удаление клиента из списка
{
lock_guard<mutex> lock(clientsMutex);
clients.erase(remove_if(clients.begin(), clients.end(),
[&clientSocket](const Client& c) { return c.socket == clientSocket; }),
clients.end());
}
closesocket(clientSocket);
return;
}
if (msg_size <= 0 || msg_size > 1024) { // Ограничение на размер сообщения
cout << "Invalid message size from client \"" << client->nickname << "\". Disconnecting.\n";
closesocket(clientSocket);
return;
}
char* msg = new (nothrow) char[msg_size + 1];
if (!msg) {
cout << "Memory allocation failed for message buffer.\n";
closesocket(clientSocket);
return;
}
memset(msg, 0, msg_size + 1);
result = recv(clientSocket, msg, msg_size, NULL);
if (result <= 0) {
cout << "Error receiving message from client \"" << client->nickname << "\". Disconnecting.\n";
delete[] msg;
// Удаление клиента из списка
{
lock_guard<mutex> lock(clientsMutex);
clients.erase(remove_if(clients.begin(), clients.end(),
[&clientSocket](const Client& c) { return c.socket == clientSocket; }),
clients.end());
}
closesocket(clientSocket);
return;
}
string fullMessage = client->nickname + ": " + msg;
delete[] msg; // Освобождение памяти сразу после использования
SaveMessageToHistory(fullMessage);
cout << "Broadcasting message: " << fullMessage << endl;
// Отправка сообщения всем клиентам
lock_guard<mutex> lock(clientsMutex); // Синхронизация доступа к clients
cout << "Clients size: " << clients.size() << endl; // Отладочный вывод
for (const Client& c : clients) {
cout << "Processing client: " << c.nickname << endl; // Отладочный вывод
if (c.socket != clientSocket) {
int msg_length = fullMessage.size();
if (send(c.socket, (char*)&msg_length, sizeof(int), NULL) == SOCKET_ERROR) {
cout << "Failed to send message length to " << c.nickname << endl;
}
if (send(c.socket, fullMessage.c_str(), msg_length, NULL) == SOCKET_ERROR) {
cout << "Failed to send message content to " << c.nickname << endl;
}
}
}
}
}
void CommandHandler() {
string command;
while (true) {
getline(cin, command);
if (command.rfind("/remove ", 0) == 0) {
string nicknameToRemove = command.substr(8);
RemoveClient(nicknameToRemove);
}
}
}
int main() {
WSAData wsaData;
WORD DLLVersion = MAKEWORD(2, 1);
if (WSAStartup(DLLVersion, &wsaData) != 0) {
cout << "Error initializing WinSock" << endl;
return 1;
}
SOCKADDR_IN addr;
int sizeofaddr = sizeof(addr);
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
addr.sin_port = htons(1111);
addr.sin_family = AF_INET;
SOCKET sListen = socket(AF_INET, SOCK_STREAM, NULL);
bind(sListen, (SOCKADDR*)&addr, sizeof(addr));
listen(sListen, SOMAXCONN);
cout << "Server is running and waiting for connections...\n";
thread commandThread(CommandHandler);
commandThread.detach();
SOCKET newConnection;
while (true) {
newConnection = accept(sListen, (SOCKADDR*)&addr, &sizeofaddr);
if (newConnection == 0) {
cout << "Error: Failed to accept connection.\n";
continue;
}
cout << "Client connected. Waiting for password...\n";
int pass_size;
int result = recv(newConnection, (char*)&pass_size, sizeof(int), NULL);
if (result <= 0) {
cout << "Error receiving password size. Closing connection.\n";
closesocket(newConnection);
continue;
}
char* pass = new char[pass_size + 1];
pass[pass_size] = '\0';
result = recv(newConnection, pass, pass_size, NULL);
if (result <= 0 || PASSWORD != pass) {
cout << "Incorrect password. Connection refused.\n";
string errorMsg = "Incorrect password";
int error_size = errorMsg.size();
send(newConnection, (char*)&error_size, sizeof(int), NULL);
send(newConnection, errorMsg.c_str(), error_size, NULL);
delete[] pass;
closesocket(newConnection);
continue;
}
delete[] pass;
string successMsg = "Password accepted";
int success_size = successMsg.size();
send(newConnection, (char*)&success_size, sizeof(int), NULL);
send(newConnection, successMsg.c_str(), success_size, NULL);
cout << "Password accepted. Waiting for nickname...\n";
int nick_size;
result = recv(newConnection, (char*)&nick_size, sizeof(int), NULL);
if (result <= 0) {
cout << "Error receiving nickname size. Closing connection.\n";
closesocket(newConnection);
continue;
}
char* nickname = new char[nick_size + 1];
nickname[nick_size] = '\0';
result = recv(newConnection, nickname, nick_size, NULL);
if (result <= 0) {
cout << "Error receiving nickname. Closing connection.\n";
delete[] nickname;
closesocket(newConnection);
continue;
}
cout << "Client \"" << nickname << "\" connected successfully!\n";
lock_guard<mutex> lock(clientsMutex);
clients.push_back({ newConnection, nickname });
cout << "Total connected clients: " << clients.size() << endl; // Отладочный вывод
delete[] nickname;
thread(ClientHandler, &clients.back()).detach();
}
WSACleanup();
return 0;
} |
|
Код клиента:
| C++ | 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
| #include <iostream>
#include <winsock2.h>
#include <string>
#include <thread>
#pragma comment(lib, "ws2_32.lib")
#pragma warning(disable:4996)
using namespace std;
SOCKET Connection;
void ClientHandler() {
int msg_size;
while (true) {
int result = recv(Connection, (char*)&msg_size, sizeof(int), NULL);
if (result <= 0 || msg_size <= 0 || msg_size > 1024) { // Проверка размера сообщения
cout << "Disconnected from server or invalid message size.\n";
closesocket(Connection);
return;
}
char* msg = new (nothrow) char[msg_size + 1];
if (!msg) {
cout << "Memory allocation failed for message buffer.\n";
closesocket(Connection);
return;
}
memset(msg, 0, msg_size + 1);
result = recv(Connection, msg, msg_size, NULL);
if (result <= 0) {
cout << "Error receiving message.\n";
delete[] msg;
closesocket(Connection);
return;
}
cout << msg << endl;
delete[] msg; // Освобождение памяти
}
}
int main() {
WSAData wsaData;
WORD DLLVersion = MAKEWORD(2, 1);
if (WSAStartup(DLLVersion, &wsaData) != 0) {
cout << "Error initializing WinSock\n";
return 1;
}
SOCKADDR_IN addr;
int sizeofaddr = sizeof(addr);
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
addr.sin_port = htons(1111);
addr.sin_family = AF_INET;
Connection = socket(AF_INET, SOCK_STREAM, NULL);
if (connect(Connection, (SOCKADDR*)&addr, sizeof(addr)) != 0) {
cout << "Failed to connect to server.\n";
return 1;
}
cout << "Connected to server. Enter password:\n";
string password;
getline(cin, password);
int pass_size = password.size();
send(Connection, (char*)&pass_size, sizeof(int), NULL);
send(Connection, password.c_str(), pass_size, NULL);
int response_size;
recv(Connection, (char*)&response_size, sizeof(int), NULL);
char* response = new char[response_size + 1];
response[response_size] = '\0';
recv(Connection, response, response_size, NULL);
cout << response << endl;
if (string(response) != "Password accepted") {
delete[] response;
closesocket(Connection);
return 1;
}
delete[] response;
cout << "Enter your nickname:\n";
string nickname;
getline(cin, nickname);
int nick_size = nickname.size();
send(Connection, (char*)&nick_size, sizeof(int), NULL);
send(Connection, nickname.c_str(), nick_size, NULL);
thread(ClientHandler).detach();
while (true) {
string msg;
getline(cin, msg);
int msg_size = msg.size();
send(Connection, (char*)&msg_size, sizeof(int), NULL);
send(Connection, msg.c_str(), msg_size, NULL);
}
return 0;
} |
|
Спасибо всем за помощь!
0
|