본문 바로가기

개발자 모드/통신

C++ UDP Server Source Code

728x90

Sever Test.egg
0.79MB

// Sever Test.cpp : 기본 프로젝트 파일입니다.

#include "stdafx.h"
#include <stdio.h>
#include <winsock.h>    // 통신을 하기 위해서 추가해야하는 헤더파일

#pragma comment( lib, "ws2_32.lib" )

using namespace System;

int main(array<System::String ^> ^args)
{

	WSAData wsa;
	SOCKADDR_IN sockAddr;
	SOCKET sock;
	char buf[ 128 ] = { 0, };

	try
	{
		if( WSAStartup( MAKEWORD( 2, 2 ), &wsa ) != 0 )
		{
			throw WSAGetLastError();
		}

		sock = socket( AF_INET, SOCK_DGRAM, 0 );
		if( sock == INVALID_SOCKET )
		{
			throw WSAGetLastError();
		}

		memset( ( void * )&sockAddr, 0, sizeof( SOCKADDR_IN ) );
		sockAddr.sin_family = AF_INET;
		sockAddr.sin_port = htons(3001 );                            // 포트를 Client와 통일해야 함
		sockAddr.sin_addr.s_addr = htonl( INADDR_ANY );

		if( bind( sock, ( SOCKADDR * )&sockAddr, sizeof( SOCKADDR ) ) == SOCKET_ERROR )
		{
			throw WSAGetLastError();
		}

		// 데이터 받기
		SOCKADDR_IN addrClient;
		int addrLen = sizeof( SOCKADDR_IN );

		while(1)
		{

		recvfrom( sock, buf, 128, 0, ( SOCKADDR * )&addrClient, &addrLen );
			printf( "-> %s\n", buf);

			
			if(!strcmp(buf,"exit"))    // exit가 들어오면 while문을 빠져 나온다.
				break;

			memset(buf,0, sizeof(char)*128);

		}

	}
	catch( int ex )
	{
		printf( "Error Code: %d\n", ex );
	}

	closesocket( sock ); // 소켓 닫기
	WSACleanup();        // 버퍼 클리어와 같은 기능  

	return 0;
}
728x90

'개발자 모드 > 통신' 카테고리의 다른 글

시리얼 통신에 유용한 프로그램  (0) 2021.05.20
C++ UDP Client Source Code  (0) 2021.03.14
RS485통신  (0) 2021.03.07
RS422 통신  (0) 2021.03.07
RS232통신  (0) 2021.03.07