Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <WinSock2.h>
- #include <WS2tcpip.h>
- #include <stdlib.h>
- #include <stdio.h>
- constexpr unsigned int BUFSIZE = 512;
- #pragma comment(lib, "ws2_32.lib")
- // 소켓 함수 오류 출력 후 종료
- 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, (LPCWSTR)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] %ws", msg, (LPCTSTR)lpMsgBuf);
- LocalFree(lpMsgBuf);
- }
- int wmain(int argc, char* argv[])
- {
- int retval;
- // 윈속 초기화
- WSADATA wsa;
- if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
- {
- return -1;
- }
- // 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 (true)
- {
- wprintf(L"Start!\n");
- // 데이터 통신에 사용할 변수
- SOCKADDR_IN clientaddr;
- int addrlen = sizeof(clientaddr);
- // accept()
- SOCKET client_sock = accept(listen_sock, (SOCKADDR*)&clientaddr, &addrlen);
- wprintf(L"accept!\n");
- if (client_sock == INVALID_SOCKET)
- {
- err_display("accept()");
- continue;
- }
- WCHAR addrBuf[BUFSIZE + 1];
- InetNtop(AF_INET, &clientaddr, (PWSTR)& addrBuf, BUFSIZE);
- wprintf(L"\n[TCP Server] Client Connect : IP = %s, Port = %d\n",
- addrBuf, ntohs(clientaddr.sin_port));
- // 클라이언트와 데이터 통신
- while (true)
- {
- char buf[BUFSIZE + 1];
- // 데이터 받기
- retval = recv(client_sock, buf, BUFSIZE, 0);
- if (retval == SOCKET_ERROR)
- {
- err_display("recv()");
- break;
- }
- else if (retval == 0)
- {
- break;
- }
- // 받은 데이터 출력
- buf[retval] = '\0';
- printf("%s", buf);
- }
- // closesocket()
- closesocket(client_sock);
- wprintf(L"\n[TCP Server] Client Disconnect : IP = %s, Port = %d\n",
- addrBuf, ntohs(clientaddr.sin_port));
- }
- // closesocket()
- closesocket(listen_sock);
- // 윈속 종료
- WSACleanup();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement