基于UDP的windows网络Socket编程

一、创建服务器端程序

#include 
#include 

void main()
{
	WORD wVersionRequested;
	WSADATA wsaData;
	int err;

	wVersionRequested = MAKEWORD( 1, 1 );

	err = WSAStartup( wVersionRequested, &wsaData );
	if ( err != 0 ) {

		return;
	}

	if ( LOBYTE( wsaData.wVersion ) != 1 ||
		HIBYTE( wsaData.wVersion ) != 1 ) {

			WSACleanup( );
			return; 
	}
	//服务器端套接字
	SOCKET sockSrc = socket(AF_INET , SOCK_DGRAM , 0) ;

	//设置服务器端地址和端口号
	SOCKADDR_IN addrSrc ;
	addrSrc.sin_addr.S_un.S_addr = htonl(INADDR_ANY) ;
	addrSrc.sin_family = AF_INET ;
	addrSrc.sin_port = htons(6000) ;

	//把服务器端套接字与地址绑定
	bind(sockSrc , (SOCKADDR *)&addrSrc , sizeof(SOCKADDR)) ;

	//预设接受客户端地址
	SOCKADDR_IN addrClient ;
	int len = sizeof(SOCKADDR) ;
	char szRecv[100] ;

	recvfrom(sockSrc , szRecv , 100 , 0 , (SOCKADDR *)&addrClient , &len) ;
	printf("%s\n" , szRecv) ;

	//关闭套接字,清理
	closesocket(sockSrc) ;
	WSACleanup() ;

	system("pause") ;
}

二、创建客户端程序

#include 
#include 

void main()
{
	WORD wVersionRequested;
	WSADATA wsaData;
	int err;

	wVersionRequested = MAKEWORD( 1, 1 );

	err = WSAStartup( wVersionRequested, &wsaData );
	if ( err != 0 ) {

		return;
	}

	if ( LOBYTE( wsaData.wVersion ) != 1 ||
		HIBYTE( wsaData.wVersion ) != 1 ) {

			WSACleanup( );
			return; 
	}
	//客户端套接字
	SOCKET sockClient = socket(AF_INET , SOCK_DGRAM , 0) ;

	//设置需要链接的服务器地址
	SOCKADDR_IN addrSrc ;
	addrSrc.sin_addr.S_un.S_addr = inet_addr("127.0.0.1") ;
	addrSrc.sin_family  = AF_INET ;
	addrSrc.sin_port = htons(6000) ;

	//发送信息
	sendto(sockClient , "hello" , strlen("hello") + 1, 0 , 
		   (SOCKADDR *)&addrSrc , sizeof(SOCKADDR)) ;

	//清理
	closesocket(sockClient) ;
	WSACleanup() ;

	//system("pause") ;
}


你可能感兴趣的:(MFC)