2 heyp113 heyp113 于 2013.08.19 15:10 提问

UDP通信中服务端接受数据计算数据包个数

UDP通信中客户端通过多线程发送数据,服务端单线程接受数据,出现的“丢包”(我在服务端计算出来的包个数)现象很严重,通过wireshark抓包发现没有任何数据包丢失,菜鸟求解答。代码如下:

/*基于LINUX的udp的通信,服务器端*/
#include
#include
#include
#include
#include
#include
#include

char buf[1024 * 32] = {0};

int main(int argc, char *argv[])
{
if (argc < 2)
{
printf("Please Input Recv Port\n");
return 1;
}
int sockfd = 0;
int recv_num = 0;
int recv_count = 0;
int client_len = 0;
volatile unsigned long res = 0;//接收数据的总大小
int len_recv_buffer = 1024 * 32;
FILE *fp;
char buffer[1024*320] = {0};

struct sockaddr_in addr;
//1、创建socket
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd == -1)
{
    printf("Create Socket Error\n");
    return -1;
}

//2、准备地址
addr.sin_family = AF_INET;
addr.sin_port = htons(atoi(argv[1]));
addr.sin_addr.s_addr = inet_addr("192.168.17.95");
client_len = sizeof(struct sockaddr_in);

//3、绑定
if (bind(sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_in)) == -1)
{
    printf("Bind Error\n");
    return 0;
}


//4、接收客户端发送来的数据
time_t t_old = time(NULL);
time_t t_now = t_old;
time_t _old = time(NULL);
time_t  _now = 0;
time_t  _interval = 0;
if ((fp = fopen("recv.txt", "a+")) == NULL)
{
    printf("Open File Error\n");
    return 1;
}
int nRecv = 0;
setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, (const char*)&nRecv, sizeof(nRecv));
while(1)
{
    memset(buf, 0 , sizeof(buf));
    recv_num = recvfrom(sockfd, buf, sizeof(buf), MSG_CTRUNC, (struct sockaddr*)&addr, &client_len);
    if (recv_num <= 0)
    {
        printf("Recv Data Error\n");
        continue;
    }

    ++recv_count;

    res += recv_num;
    t_now = time(NULL);
    _now = time(NULL);
    _interval = _now - _old;
   // if (t_now - t_old >= 1)
    {
     //   printf("recv_num= %d\n", recv_num);
        sprintf(buffer,  "接受数据总大小:res = %lu kbytes, 数据包个数:%d 接受时间:%d s\n", res/1024, recv_count, _interval);
        if ((fputs(buffer,fp)) == 0)
        {
            printf("Fwrite Error\n");
            return 1;
        }
        fflush(fp);
        printf("接收数据总大:res = %lu kbytes, 数据包个数:%d 接受时间:%d s\n", res / 1024, recv_count, _interval);

        t_old = t_now;
    }
}

free(fp);
fp = NULL;
return 0;
}

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!