UDP协议的WinSock API编程示例

Server 端:

        WORD wVersion;
        WSADATA wsaData;
        sockaddr_in server_addr,client_addr;
        char buff[1024];
        wVersion=MAKEWORD(2,2);
  if (WSAStartup(wVersion,&wsaData)!=0)
        {
            printf("无法加载 WSAStartup()!/n");
        }
        SOCKET server=socket(AF_INET,SOCK_DGRAM,0);
        if (server==INVALID_SOCKET)
        {
            printf("The requested socket is invalid!/n");
        }
       
        server_addr.sin_family=AF_INET;
        server_addr.sin_port=htons(5000);
        server_addr.sin_addr.S_un.S_addr=INADDR_ANY;
        bind(server,(sockaddr*)&server_addr,sizeof(server_addr));
        int iLen=sizeof(client_addr);
        while (1)
        {
            recvfrom(server,buff,sizeof(buff),0,(sockaddr*)&client_addr,&iLen);
            printf("Client said: %s",buff);
            strcpy(buff,"I am a server!!/n");
            sendto(server,buff,sizeof(buff),0,(sockaddr*)&client_addr,sizeof(client_addr));
        }
        closesocket(server);
        WSACleanup();

Client 端:  

 WORD wVersion=0x0202;
        WSADATA wsaData;
        sockaddr_in server_addr;
        server_addr.sin_addr.S_un.S_addr=inet_addr("192.168.1.97");
        server_addr.sin_family=AF_INET;
        server_addr.sin_port=htons(5000);
        char buff[1024];
        int iLen=sizeof(server_addr);
        if (WSAStartup(wVersion,&wsaData)!=0)
        {
            printf("WSAStartup Error!");
            return 0;
        }
        SOCKET client=socket(AF_INET,SOCK_DGRAM,0);
        if (client==INVALID_SOCKET)
        {
            printf("create socket fail!");
            return 0;
        }
        strcpy(buff,"I am a client!/n");
        sendto(client,buff,sizeof(buff),0,(sockaddr*)&server_addr,iLen);
        recvfrom(client,buff,sizeof(buff),0,(sockaddr*)&server_addr,&iLen);
        printf("Server Said: %s",buff);
        closesocket(client);
        WSACleanup();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值