码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-07-25 22:53:10      阅读:283      评论:0      收藏:0      [点我收藏+]

标签:

服务端为上位机部分。客户端为下位机部分,下位机有多个MCU,所以就会有不同的IP地址。上位机实现接收下位机的信息,并区别不同的IP发来的信息。通信端口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 服务器与多个客户端通信

标签:

原文地址:http://www.cnblogs.com/blue-sky-hahaha/p/4676714.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!