Thinking Different




c 기반 iocp + list echo서버 소스입니다.

list 객체를 이용하여 접속되는 클라이언트를 list에 넣고 클라이언트에서 날아오는 메시지를 모든 클라이언트들에게 다시 에코서비스하는 소스입니다. 


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
#include <winsock2.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <list>
#include <process.h>
 
CRITICAL_SECTION cs;
 
using namespace std;
 
#define BUFSIZE 512
 
//#define IO_ACCEPT    1
//#define IO_READ        0
// 소켓 정보 저장을 위한 구조체
typedef enum IO_TYPE { IO_READ, IO_ACCEPT };
struct SOCKETINFO
{
    OVERLAPPED overlapped;
    SOCKET sock;
    IO_TYPE    io_type;
    char buf[BUFSIZE+1];
    WSABUF wsabuf;
};
list<SOCKETINFO*> g_sock;
 
// 소켓 입출력 함수
DWORD WINAPI WorkerThread(LPVOID arg);
// 오류 출력 함수
void err_quit(char *msg);
void err_display(char *msg);
 
int main(int argc, char* argv[])
{
    InitializeCriticalSection(&cs);
    int retval;
 
    // 윈속 초기화
    WSADATA wsa;
    if(WSAStartup(MAKEWORD(2,2), &wsa) != 0)
        return -1;
 
    // 입출력 완료 포트 생성
    HANDLE hcp = CreateIoCompletionPort(
        INVALID_HANDLE_VALUE, NULL, 0, 0);
    if(hcp == NULL) return -1;
 
    // CPU 개수 확인
    SYSTEM_INFO si;
    GetSystemInfo(&si);
 
    // (CPU 개수 * 2)개의 작업자 스레드 생성
    HANDLE hThread;
    DWORD ThreadId;
    for(int i=0; i<(int)si.dwNumberOfProcessors*2; i++){
        hThread = CreateThread(NULL, 0, WorkerThread, hcp, 0, &ThreadId);
        if(hThread == NULL) return -1;
        CloseHandle(hThread);
    }
 
    // socket()
    SOCKET listen_sock = socket(AF_INET, SOCK_STREAM, 0);
    if(listen_sock == INVALID_SOCKET) err_quit("socket()");
 
    // bind()
    SOCKADDR_IN serveraddr;
    ZeroMemory(&serveraddr, sizeof(serveraddr));
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_port = htons(9000);
    serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
    retval = bind(listen_sock, (SOCKADDR *)&serveraddr, sizeof(serveraddr));
    if(retval == SOCKET_ERROR) err_quit("bind()");
    
    // listen()
    retval = listen(listen_sock, SOMAXCONN);
    if(retval == SOCKET_ERROR) err_quit("listen()");
 
    while(1){
        // accept()
        SOCKADDR_IN clientaddr;
        int addrlen = sizeof(clientaddr);
        SOCKET client_sock = accept(listen_sock, (SOCKADDR *)&clientaddr, &addrlen);
        if(client_sock == INVALID_SOCKET){
            err_display("accept()");
            continue;
        }
        printf("[TCP 서버] 클라이언트 접속: IP 주소=%s, 포트 번호=%d\n", 
            inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port));
 
        // 소켓과 입출력 완료 포트 연결
        HANDLE hResult = CreateIoCompletionPort((HANDLE)client_sock, hcp, 
            (DWORD)client_sock, 0);
        if(hResult == NULL) return -1;
 
        // 소켓 정보 구조체 할당
        SOCKETINFO *ptr = new SOCKETINFO;
        if(ptr == NULL){
            printf("[오류] 메모리가 부족합니다!\n");
            break;
        }
        g_sock.push_back(ptr);
 
        ZeroMemory(&(ptr->overlapped), sizeof(ptr->overlapped));
        ptr->sock = client_sock;
        ptr->wsabuf.buf = ptr->buf;
        ptr->wsabuf.len = BUFSIZE;
        ptr->io_type = IO_ACCEPT;
 
        // 비동기 입출력 시작
        DWORD recvbytes;
        DWORD flags = 0;
        retval = WSARecv(client_sock, &(ptr->wsabuf), 1, &recvbytes,
            &flags, &(ptr->overlapped), NULL);
        if(retval == SOCKET_ERROR){
            if(WSAGetLastError() != ERROR_IO_PENDING){
                err_display("WSARecv()0");
            }
            continue;
        }
    }
    
    closesocket(listen_sock);
 
    list<SOCKETINFO*>::iterator it = g_sock.begin();
    while(it != g_sock.end())
    {
        SOCKETINFO *a = *it;
        closesocket(a->sock);
        g_sock.remove(a);
        it++;
    }
    g_sock.clear();
 
    // 윈속 종료
    WSACleanup();
    DeleteCriticalSection(&cs);
    return 0;
}
 
DWORD WINAPI WorkerThread(LPVOID arg)
{
    HANDLE hcp = (HANDLE)arg;
    int retval;
    DWORD cbTransferred;
    SOCKET client_sock;
    SOCKETINFO *ptr = NULL;
    
    while(1)
    {
        // 비동기 입출력 완료 기다리기
        retval = GetQueuedCompletionStatus(hcp, &cbTransferred,    (LPDWORD)&client_sock, (LPOVERLAPPED *)&ptr, INFINITE);
 
        // 클라이언트 정보 얻기
        SOCKADDR_IN clientaddr;
        int addrlen = sizeof(clientaddr);
        getpeername(ptr->sock, (SOCKADDR *)&clientaddr, &addrlen);
        
        // 연결종료?
        if(retval == 0 || cbTransferred == 0)
        {
            if(retval == 0)
            {
                DWORD temp1, temp2;
                WSAGetOverlappedResult(ptr->sock, &(ptr->overlapped), &temp1, FALSE, &temp2);
                err_display("WSAGetOverlappedResult()");
            }
 
            EnterCriticalSection(&cs);
            g_sock.remove((SOCKETINFO*)ptr);
            LeaveCriticalSection(&cs);
 
            closesocket(ptr->sock);
            printf("[TCP 서버] 클라이언트 종료: IP 주소=%s, 포트 번호=%d\n", 
                            inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port));
            delete ptr;
            continue;
        }
 
        if(ptr)    // 정상적인 데이터?
        {
            ptr->buf[cbTransferred] = NULL;
            ////////////////////////
            //  프로토콜 처리 시작
            if(ptr->io_type == IO_ACCEPT)    // 접속 후 처리
            {
                printf("초기 데이터 : %s\n", ptr->buf);
                printf("사이즈 : %d\n", g_sock.size());
                // 데이터 에코처리
 
                EnterCriticalSection(&cs);
                list<SOCKETINFO*>::iterator it = g_sock.begin();
                while(it != g_sock.end())
                {
                    SOCKETINFO*a = *it;
                    send(a->sock, ptr->buf, cbTransferred, 0);
                    it++;
                }
                LeaveCriticalSection(&cs);
            }
            else if(ptr->io_type == IO_READ)    // 전송IO작업이 끝나면 여기로옴 데이터 받은 후 처리
            {
                printf("READ 데이터 : %s\n", ptr->buf);
 
                // 데이터 에코처리
//                send(ptr->sock, ptr->buf, cbTransferred, 0);
 
                EnterCriticalSection(&cs);
                list<SOCKETINFO*>::iterator it = g_sock.begin();
                while(it != g_sock.end())
                {
                    SOCKETINFO*a = *it;
                    send(a->sock, ptr->buf, cbTransferred, 0);
                    it++;
                }
                LeaveCriticalSection(&cs);
            }
            ///////////////////////
            //  프로토콜 처리 종료
            //
            //
 
            //////////////////////////////////////
            // 처리후 다시 데이터 받음////////////
            ZeroMemory(&(ptr->overlapped), sizeof(ptr->overlapped));
            ptr->wsabuf.buf = ptr->buf;
            ptr->wsabuf.len = BUFSIZE;
            ptr->io_type = IO_READ;
 
            DWORD recvbytes;
            DWORD flags = 0;
            retval = WSARecv(ptr->sock, &(ptr->wsabuf), 1, &recvbytes, &flags, &(ptr->overlapped), NULL);
            if(retval == SOCKET_ERROR){
                if(WSAGetLastError() != WSA_IO_PENDING){
                    err_display("WSARecv()1");
                }
                continue;
            }
            //////////////////////////////////////
        }
    }
 
    return 0;
}
 
// 소켓 함수 오류 출력 후 종료
void err_quit(char *msg)
{
    LPVOID lpMsgBuf;
    FormatMessage( 
        FORMAT_MESSAGE_ALLOCATE_BUFFER|
        FORMAT_MESSAGE_FROM_SYSTEM,
        NULL, WSAGetLastError(),
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR)&lpMsgBuf, 0, NULL);
    MessageBox(NULL, (LPCTSTR)lpMsgBuf, msg, MB_ICONERROR);
    LocalFree(lpMsgBuf);
    exit(-1);
}
 
// 소켓 함수 오류 출력
void err_display(char *msg)
{
    LPVOID lpMsgBuf;
    FormatMessage( 
        FORMAT_MESSAGE_ALLOCATE_BUFFER|
        FORMAT_MESSAGE_FROM_SYSTEM,
        NULL, WSAGetLastError(),
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR)&lpMsgBuf, 0, NULL);
    printf("[%s] %s", msg, (LPCTSTR)lpMsgBuf);
    LocalFree(lpMsgBuf);
}