C ++套接字不断接收相同的数据

C++ socket keeps receiving the same data

我正在使用此代码通过套接字从传感器接收数据。问题是 for 循环的每次迭代我都会收到相同的输出。但是,每次我 运行 代码时,我都会收到不同的号码,但同样的号码会不断重复。传感器应该每次发送不同的数据,但这里不是这种情况。

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <netdb.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "port.h"

#define BUFSIZE 2048

int
main(int argc, char **argv)
{
    struct sockaddr_in myaddr;  /* our address */
    struct sockaddr_in remaddr; /* remote address */
    socklen_t addrlen = sizeof(remaddr);        /* length of addresses */
    int recvlen;            /* # bytes received */
    int fd;             /* our socket */
    int msgcnt = 0;         /* count # of messages we received */
    unsigned char buf[BUFSIZE]; /* receive buffer */


    /* create a UDP socket */

    if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
        perror("cannot create socket\n");
        return 0;
    }

    /* bind the socket to any valid IP address and a specific port */

    memset((char *)&myaddr, 0, sizeof(myaddr));
    myaddr.sin_family = AF_INET;
    myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    myaddr.sin_port = htons(SERVICE_PORT);

    if (bind(fd, (struct sockaddr *)&myaddr, sizeof(myaddr)) < 0) {
        perror("bind failed");
        return 0;
    }

    /* now loop, receiving data and printing what we received */

    printf("waiting on port %d\n", SERVICE_PORT);
        printf("%s \n \n", "We recieve 10 packets just to confirm the communication");


    recvlen = recvfrom(fd, buf, BUFSIZE, 0, (struct sockaddr *)&remaddr, &addrlen);
        if (recvlen > 0) {
            buf[recvlen] = 0;
            printf("received message: \"%u\" (%d bytes)\n", buf, recvlen);
        }
        else
            printf("uh oh - something went wrong!\n");
        sprintf(buf, "ack %d", msgcnt++);
        printf("sending response \"%u\"\n", buf);
        if (sendto(fd, buf, strlen(buf), 0, (struct sockaddr *)&remaddr, addrlen) < 0)
            perror("sendto");

    int temp = recvlen;

    for (;;) {

    recvlen = recvfrom(fd, buf, BUFSIZE, 0, (struct sockaddr *)&remaddr, &addrlen);
    if (recvlen > 0) {
            buf[recvlen] = 0;
            printf("received message: \"%u\" (%d bytes)\n", buf, recvlen);

    }



}
}

编辑: 这是我 运行 代码两次时的输出: trial runtrial run 2

我认为问题不在于您的网络代码,而在于您的 printf() 调用:

        printf("received message: \"%u\" (%d bytes)\n", buf, recvlen);

您正在指定 %u 来打印出 buf 的内容,但 buf 是一个字符数组(不是无符号整数),因此您可能希望使用 %s相反。