-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.cpp
More file actions
112 lines (88 loc) · 2.47 KB
/
server.cpp
File metadata and controls
112 lines (88 loc) · 2.47 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
#include <iostream>
#include<stdio.h>
#include<WinSock2.h>
#include<WS2tcpip.h>
#include<tchar.h>
#include<thread>
#include <vector>
using namespace std;
int port = 12345;
#pragma comment(lib, "ws2_32.lib")
bool initialize() {
WSADATA wsaData;
return WSAStartup(MAKEWORD(2, 2), &wsaData)==0;
}
void InteractWithClient(SOCKET clientSocket, vector<SOCKET>& clients) {
cout << "connected with client" << endl;
char buffer[4096];
while (1) {
int bytesrecvd = recv(clientSocket, buffer, sizeof(buffer), 0);
if (bytesrecvd <= 0) {
cout << "client disconnected" << endl;
break; // Exit the loop when client disconnects
}
string message(buffer, bytesrecvd);
cout << "message from client: " << message << endl;
for (auto client : clients) {
if (client != clientSocket) {
send(client, message.c_str(), message.length(), 0);
}
}
}
// Remove the client from the vector after the loop
auto it = find(clients.begin(), clients.end(), clientSocket);
if (it != clients.end()) {
clients.erase(it);
}
closesocket(clientSocket);
}
int main() {
if (!initialize()) {
cout << "Initialization failed." << endl;
return 1;
}
//sockets creation
SOCKET listenSocket = socket(AF_INET, SOCK_STREAM, 0);
if (listenSocket == INVALID_SOCKET) {
cout << "socket failed" << endl;
return 1;
}
//crt structure
sockaddr_in serveraddr;
serveraddr.sin_family = AF_INET;
serveraddr.sin_port = htons(port);
//convert ip24
if (InetPton(AF_INET, _T("0.0.0.0"), &serveraddr.sin_addr) != 1) {
cout << "setting addr failed"<<endl;
closesocket(listenSocket);
WSACleanup();
return 1;
}
if (bind(listenSocket, reinterpret_cast<sockaddr*>(&serveraddr), sizeof(serveraddr)) == SOCKET_ERROR) {
cout << "bind fILEd" << endl;
closesocket(listenSocket);
WSACleanup();
return 1;
}
//listen
if (listen(listenSocket, SOMAXCONN) == SOCKET_ERROR) {
cout << "listen failed" << endl;
closesocket(listenSocket);
WSACleanup();
}
cout << "Server started listning on " << port << endl;
//acccept
vector<SOCKET> clients;
while (1) {
SOCKET clientSocket = accept(listenSocket, nullptr, nullptr);
if (clientSocket == INVALID_SOCKET) {
cout << "invaalid clnt socket" << endl;
}
clients.push_back(clientSocket);
thread t1(InteractWithClient, clientSocket, std::ref(clients));
t1.detach();
}
closesocket(listenSocket);
WSACleanup();
return 0;
}