-
Notifications
You must be signed in to change notification settings - Fork 0
/
ThreadServer.cpp
84 lines (66 loc) · 1.82 KB
/
ThreadServer.cpp
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
#include <iostream>
#include <WinSock2.h>
#include <Windows.h>
#include <process.h>
#include <vector>
#include <set>
#include <map>
#pragma comment(lib, "ws2_32")
std::set<SOCKET> SessionList;
CRITICAL_SECTION SessionCS;
unsigned WINAPI WorkerThread(void* Arg)
{
SOCKET ClientSocket = *((SOCKET*)Arg);
while (true)
{
char Buffer[1024] = { 0, };
int RecvByte = recv(ClientSocket, Buffer, sizeof(Buffer), 0);
if (RecvByte <= 0)
{
EnterCriticalSection(&SessionCS);
SessionList.erase(ClientSocket);
LeaveCriticalSection(&SessionCS);
closesocket(ClientSocket);
break;
}
else
{
EnterCriticalSection(&SessionCS);
for (auto ConnectSocket : SessionList)
{
int SendLength = send(ConnectSocket, Buffer, RecvByte, 0);
}
LeaveCriticalSection(&SessionCS);
}
}
return 0;
}
int main()
{
InitializeCriticalSection(&SessionCS);
WSAData wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
SOCKET ListenSocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
SOCKADDR_IN ListenSockAddr;
memset(&ListenSockAddr, 0, sizeof(ListenSockAddr));
ListenSockAddr.sin_family = AF_INET;
ListenSockAddr.sin_addr.s_addr = INADDR_ANY;
ListenSockAddr.sin_port = htons(5001);
bind(ListenSocket, (SOCKADDR*)&ListenSockAddr, sizeof(ListenSockAddr));
listen(ListenSocket, 5);
while (true)
{
SOCKADDR_IN ClientSockAddr;
memset(&ClientSockAddr, 0, sizeof(ClientSockAddr));
int ClientSockAddrLength = sizeof(ClientSockAddr);
SOCKET ClientSocket = accept(ListenSocket, (SOCKADDR*)&ClientSockAddr, &ClientSockAddrLength);
HANDLE ThreadHandle = (HANDLE)_beginthreadex(0, 0, WorkerThread, (void*)&ClientSocket, 0, 0);
EnterCriticalSection(&SessionCS);
SessionList.insert(ClientSocket);
LeaveCriticalSection(&SessionCS);
}
closesocket(ListenSocket);
WSACleanup();
DeleteCriticalSection(&SessionCS);
return 0;
}