UDP 服务器与多个客户端通信

服务端与多个客户端进行连接,接收客户端发送来的信息。通信端口5000

服务端:IP设置为196.168.1.100

   int sock_fd = socket(PF_INET, SOCK_DGRAM, 0);

     if (sock_fd < 0)
     {
         printf ( "error: Create Socket Failed!" );
         return  -1;
     }
     
     struct  sockaddr_in sock_addr;
     sock_addr.sin_family = AF_INET;
     sock_addr.sin_port = htons(5000);
     sock_addr.sin_addr.s_addr = htonl(INADDR_ANY);
     memset (sock_addr.sin_zero, 0x00, 8);
     
     try
     {
         if (bind(sock_fd, ( struct  sockaddr *)&sock_addr, sizeof ( struct  sockaddr)) != 0)   //绑定
         {
             printf ( "error: Bind Socket Failed!" );
             res = -1;
             throw  res;
         }
         
         char  buf[256];
         int  recvslen;
         struct  sockaddr_in from;
         uint32_t fromlen = sizeof(struct sockaddr);
         while (1)
         {
             if ((recvslen = recvfrom(sock_fd, recvs, 256, 0, ( struct  sockaddr *)&from , &fromlen)) == -1)
             {
                 printf ( "error: Receiving Failed!" );
                 res = -1;
                 throw  res;
             }
             else
             {
                 if (recvslen < 256)
                     *(recvs+recvslen) = '\0' ;
                 else
                     *(recvs+255) = '\0' ;
        if (from.sin_addr.s_addr == inet_addr(196.168.1.2)){      //根据from的IP地址来确定是接收的哪个IP发来的信息
                   printf ( "Received data:\n[%s] from 196.168.1.2\n" ,recvs);
        }
             }
         }
     }
     catch (...)
     {
         printf ( "error catched~" );
     }
 
客户端:以IP 196.168.1.2为例

 int sock_fd = socket(PF_INET, SOCK_DGRAM, 0);

     if (sock_fd < 0)
     {
         printf ( "error: Create Socket Failed!" );
         return  -1;
     }
     
     struct  sockaddr_in addrTo;
    addrTo .sin_family = AF_INET;
    addrTo .sin_port = htons(5000);
    addrTo .sin_addr.s_addr = htonl("196.168.1.100");  //服务端的地址
     memset (addrTo.sin_zero, 0x00, 8);
     
     try
     {
         char  buf[256] = "This is from 196.168.1.2";
         int n ;
         struct  sockaddr_in to;
         uint32_t tolen = sizeof(struct sockaddr);
         while (1)
         {
             if ((n= recvfrom(sock_fd, recvs, 5000, 0, ( struct  sockaddr *)&addrTo, &tolen)) == -1)
             {
                 printf ( "error: Receiving Failed!" );
                 res = -1;
                 throw  res;
             }
             else if (n > 0)
             {  
        printf ( "Send data to 196.168.1.100\n" );
             }
         }
     }
     catch (...)
     {
         printf ( "error catched~" );
     }

你可能感兴趣的:(UDP)