gpt4 book ai didi

c - pthread_create 仅当套接字上有数据可用时

转载 作者:行者123 更新时间:2023-11-30 17:35:46 30 4
gpt4 key购买 nike

我的服务器正在向客户端发送 udp 数据报,并在数据包丢失时从客户端接收 NACK 数据报。我想创建一个线程来处理每个 NACK 数据包,但只有当我有东西要从客户端接收时我才想创建线程。为此,我想使用 select ,如果套接字上有东西,则创建新线程并调用 recvfrom 函数。我定义了 timeval 结构并用 0 填充它,因为我不想等待,我希望在服务器发送时选择“监听套接字”,但选择总是返回我 0 ....是否有任何解决方案不同的想法如何并行发送和接收?

int main (void) {

struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 0;

fd_set readfds;
FD_ZERO(&readfds);

// Create the socket
if((sd = socket (AF_INET, SOCK_DGRAM, 0)) < 0) {
printf("Server socket could not be created : %s\n",strerror(errno));
return 0;
}


// Non-blocking socket
fcntl(sd,F_SETFL,O_NONBLOCK);

FD_ZERO(&readfds);
FD_SET(sd,&readfds);

//Allow multiple applications to receive datagrams that are destined to the same local port number.
if(setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) == -1){
printf("Setsockopt error: %s", strerror(errno));
return 1;
}

// Initialize the group sockaddr structure with a multicast address of 226.1.1.1 and port 5555.
memset((char *) &multiaddr, 0, sizeof(multiaddr));
multiaddr.sin_family = AF_INET;
multiaddr.sin_addr.s_addr = inet_addr(IP_GROUP);
multiaddr.sin_port = htons(PORT_NUM);

// Fill the structure udp_srv with informations like multicast address,port number and socket
strcpy(udp_srv.peer_address,inet_ntoa(multiaddr.sin_addr));
udp_srv.peer_port = multiaddr.sin_port;
udp_srv.udp_sd = sd;

if((fd = open("text.txt",O_RDONLY , 0777))== -1) {
printf("Error while opening txt file!\n",strerror(errno));
return 1;
} else {
while(1) {
sleep(1);
if((numRead = read(fd,tmp,512)) != 0) {
tmp[numRead]='\0';
strcpy(pack.buffer,tmp);
//function for sending data until EOF !
sent = data_sent(udp_srv,&pack);
} else {
sent = last_data_sent(udp_srv,&pack);
close(sd);
exit(1);
}
rv = select(sd + 1, &readfds, NULL, NULL, &tv);

if(rv > 0) {

// Create a new thread and call recvfrom in nack_processing function !
if(pthread_create(&cln_thread, NULL, nack_processing, (void *) &arg)){
printf("Pthrad create errorr\n",strerror(errno));
continue;
}
}
}
}
return 0;
}

最佳答案

一些建议。

if(rv == 1) 更改为 if(rv > 0) 并提供一些时间

struct timeval tv;
tv.tv_sec = 5;


fd_set readfds;
rv = select(sd + 1, &readfds, NULL, NULL, &tv);
rv = select(sd + 1, &readfds, (fd_set *)0, (fd_set *)0, &tv);

尝试一下

关于c - pthread_create 仅当套接字上有数据可用时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22912965/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com