《孙鑫VC视频》- UDP网络编程

服务器端(接收端)程序:
1、创建套接字(socket)。
2、将套接字绑定到一个本地地址和端口上(bind)。
3、等待接收数据(recvfrom)。
4、关闭套接字。


客户端(发送端)程序:
1、创建套接字(socket)。
2、向服务器发送数据(sendto)。
3、关闭套接字。


服务器端代码:

    /*
     *UDP Server 
     *2008-12-04
     */
    #include <winsock2.h>
    #include <stdio.h>
    
    void main(){
    	//初始化
    	WORD wVersionRequired;
    	WSAData wsaData;
    	wVersionRequired = MAKEWORD(2,2);
    	
    	WSAStartup(wVersionRequired,&wsaData);
    
    	//创建socket
    	SOCKET server;
    	server = socket(AF_INET,SOCK_DGRAM,0);
    
    	//绑定
    	SOCKADDR_IN addr;
    	addr.sin_family = AF_INET;
    	addr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
    	addr.sin_port = htons(6006);
    	bind(server,(SOCKADDR*)&addr,sizeof(SOCKADDR));
    	
    	//接收
    	char recvBuf[100];
    	int recvLen;
    	SOCKADDR_IN clientAddr;
    	int fromLen;
    	recvLen = 100;
    	fromLen = sizeof(SOCKADDR);
    	recvfrom(server,recvBuf,recvLen,0,(SOCKADDR*)&clientAddr,&fromLen);
    	printf("Receive:%s",recvBuf);
    
    	//发送
    	char * sendBuf;
    	int sendLen;
    	sendBuf = "Message from Server!\n";
    	sendLen = strlen(sendBuf) + 1;
    	sendto(server,sendBuf,sendLen,0,(SOCKADDR*)&clientAddr,fromLen);
    
    	//关闭
    	closesocket(server);
    	WSACleanup();
    }
     

    客户端程序:

      /*
       *UDP Client 
       *2008-12-04
       */
      #include <winsock2.h>
      #include <stdio.h>
      
      void main(){
      	WORD wVersionRequired;
      	WSAData wsaData;
      	wVersionRequired = MAKEWORD(2,2);
      	WSAStartup(wVersionRequired,&wsaData);
      
      	SOCKET client;
      	client = socket(AF_INET,SOCK_DGRAM,0);
      
      	char sendBuf[100];
      	int len;
      	SOCKADDR_IN addr;
      	int toLen;
      	char *temp = "Message from Client!\n";
      	sprintf(sendBuf,"%s",temp);
      	len = strlen(sendBuf)+1;
      	addr.sin_family = AF_INET;
      	addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
      	addr.sin_port = htons(6006);
      	toLen = sizeof(SOCKADDR);
      	sendto(client,sendBuf,len,0,(SOCKADDR*)&addr,toLen);
      
      	char recvBuf[100];
      	int recvLen;
      	SOCKADDR_IN addr_in;
      	int fromLen;
      	recvLen = 100;
      	fromLen = sizeof(SOCKADDR);
      	recvfrom(client,recvBuf,recvLen,0,(SOCKADDR*)&addr_in,&fromLen);
      	printf("Receive:%s",recvBuf);
      
      	closesocket(client);
      	WSACleanup();
      }
       

        你可能感兴趣的:(编程,socket,vc++)