728x90
Server Source
// 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;
}
Cleint Source
// Client 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;
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 ); // PORT는 Server와 동일하게 통일
sockAddr.sin_addr.s_addr = inet_addr( "192.168.2.11" ); // Source 장비의 IP를 입력
// 데이터 보내기
sendto( sock, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", strlen( "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ), 0, ( SOCKADDR * )&sockAddr, sizeof( SOCKADDR_IN ) );
Sleep(1000);
}
catch( int ex )
{
printf( "Error Code: %d\n", ex );
}
closesocket( sock );
WSACleanup();
return 0;
}
https://www.youtube.com/watch?v=aQcyudLkaZs&t=14s
서버 실행파일을 먼저 실행시키고
클라이언트를 실행해서 서버에서 받은 메세지를 표현하게 코드를 짬...
참고하세요
올린 소스는 클라이언트가 1번 보내는거임
728x90