Windows Programming/Windows Socket

Windows Socket (Server)

Privat3 2022. 1. 11. 11:38

윈도우 기반 서버 소켓 기본 코드 입니다.

#include <stdio.h>
#include <stdlib.h>
#include <WinSock2.h>
#include <WS2tcpip.h>
#pragma comment(lib, "ws2_32")

#define PORT 8088
#define MAXSIZE 256
#define PACKET_SIZE 1024

int main(int argc, char *argv[]) 
{

	WSADATA wsaData;
	SOCKET hListen;
	int nRecv = 0;

	char buf[MAXSIZE] = { 0, };
	WSAStartup(MAKEWORD(2, 2), &wsaData);

	hListen = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (hListen == -1) ErrorMsg("Socket Error!");

	SOCKADDR_IN listnAddr = { 0, };
	listnAddr.sin_family = AF_INET;
	listnAddr.sin_port = htons(PORT);
	listnAddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);

	if (bind(hListen, (SOCKADDR *)&listnAddr, sizeof(listnAddr)) == -1)
		printf("Bind() Error!");

	if (listen(hListen, SOMAXCONN) == -1) 
		printf("Listen() Error!");

	SOCKADDR_IN ClntAddr = { 0, };
	printf("Server Working....\n");
	int iClntSize = sizeof(ClntAddr);
	int i = 1;
	
	while (1) 
	{
		SOCKET hClient = accept(hListen, (SOCKADDR *)&ClntAddr, &iClntSize);
		if (hClient == -1)  
        	printf("Accept() Error!"); 
        //
		nRecv = recv(hClient, buf, PACKET_SIZE, 0);
		if (nRecv == -1) 
        	printf("Recv() Error!");
        //
		printf("Rev msg : %s \n", buf);
	}
    
	closesocket(hListen);
	WSACleanup();
	return 0;
}