在C中接收一个UDP数据包并继续循环

时间:2016-08-11 00:02:51

标签: c sockets char udp

我尝试通过udp接收一个数据包。 我的问题是,如果没有数据发送,循环会立即停止。(我不会离开循环)

如果没有数据发送,我的char msg是否会丢失其值?

如果有人知道如何防止这种情况,如果你能与我分享,我会很高兴

仅供参考:我收到的数据格式为i:j(i从0到3,j从0到255.目前我只对“:”之前的部分感兴趣,这就是为什么我要剪掉它)

        GetBLCtrlADRExecuteOrder(&BLCtrlADRExecuteOrder[0]);

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

        struct sockaddr_in serverAdress;
        serverAdress.sin_family = PF_INET;
        serverAdress.sin_port = htons(4999);
        serverAdress.sin_addr.s_addr = INADDR_ANY;

        bind(serverSocket, (struct sockaddr*) &serverAdress,
                sizeof(serverAdress));

        while (1) {

            char msg[7];
            struct sockaddr_in client;

            socklen_t adressSize = sizeof(client);
            recvfrom(serverSocket, msg, sizeof(msg), 0,
                    (struct sockaddr*) &client, &adressSize);

            printf("Here is the message: %s\n", msg);

            char *c = strtok(msg, ":");
            printf("toke %s \n", c);

            if (strcmp(c, v0) == 0) {
                pwmValue0 = 10;
                sendBuffer0[0] = pwmValue0;
                g_lldI2c_WriteI2c_bl(BLCtrlADRExecuteOrder[0],
                        &sendBuffer0[0], 1);
            }

            if (strcmp(c, v1) == 0) {

                pwmValue1 = 10;
                sendBuffer1[0] = pwmValue1;
                g_lldI2c_WriteI2c_bl(BLCtrlADRExecuteOrder[1],
                        &sendBuffer1[0], 1);

            }

            if (strcmp(c, v2) == 0) {
                pwmValue2 = 10;
                sendBuffer2[0] = pwmValue2;
                g_lldI2c_WriteI2c_bl(BLCtrlADRExecuteOrder[2],
                        &sendBuffer2[0], 1);

            }

            if (strcmp(c, v3) == 0) {
                pwmValue3 = 10;
                sendBuffer3[0] = pwmValue3;
                g_lldI2c_WriteI2c_bl(BLCtrlADRExecuteOrder[3],
                        &sendBuffer3[0], 1);

            }


        }

    }

0 个答案:

没有答案