简体   繁体   中英

UDP PACKET TRANSFERRING

I am using a UDP child process and i want to send the output of the command given by the father process to the client (client is connected to father with TCP). What i've done is shown below but it's not working as i want. I need to send the output as messages of 512 bytes maximum (ie if the message is 600 bytes then it should send 512 + 88 bytes). The client should also exit when he gets the messages but it won't exit in my case. I tried to use dup2 as i've seen through examples but it doesn't work on UDP since no connection is established

//child process
FILE *fp;
fp = popen(s, "r"); //s = "ls"
while (fgets(buffer, sizeof(buffer), fp)) {
    sendto(sockfd, buffer, strlen(buffer)+1,  MSG_CONFIRM, (const struct sockaddr *)&servaddr, sizeof(servaddr)); 
}

pclose(fp);       
n = recvfrom(sockfd, (char *)buffer, 512, MSG_WAITALL, (struct sockaddr *)&servaddr, &len); 
printf("Client : %s\n", buffer); 

close(sockfd); 

//client process
int len; 

len = sizeof(cliaddr); 

while(recvfrom(sockfd, (char *)buffer, MAXLINE,  MSG_WAITALL, ( struct sockaddr *)&cliaddr, &len)){ 
    printf("%s", buffer);
}
sendto(sockfd, (const char *)hello, strlen(hello), MSG_CONFIRM, (const struct sockaddr *) &cliaddr, len); 
printf("Hello message sent.\n"); 

return 0; 

The while loop in the client will never exit.

By default a call to recvfrom is blocking. That means it will wait until it received data, so if no data is coming it just sits there. Unlike TCP there's no connection that can be closed so recvfrom won't return 0.

You need to have some way for the server to tell the client that it's done sending data so that the client knows when to respond, perhaps a 1 byte message with the byte set to 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM