我正在尝试将模拟数据从客户端发送到服务器,并使用UDP进行完美连接。我大约每3个发送会刺激一次打包丢失。如果我取消注释recv部分,它将仅在发送一次后停止! idk为何如此。我包括了双方的代码,并注释了recv部分。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define PORT 8080
#define MAXLINE 1024
// Driver code
int main() {
int sockfd;
char buffer[MAXLINE];
char *hello = "Hello from server";
struct sockaddr_in servaddr, cliaddr;
// Creating socket file descriptor
if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
memset(&servaddr, 0, sizeof(servaddr));
memset(&cliaddr, 0, sizeof(cliaddr));
// Filling server information
servaddr.sin_family = AF_INET; // IPv4
servaddr.sin_addr.s_addr = INADDR_ANY;
servaddr.sin_port = htons(PORT);
// Bind the socket with the server address
if ( bind(sockfd, (const struct sockaddr *)&servaddr,
sizeof(servaddr)) < 0 )
{
perror("bind failed");
exit(EXIT_FAILURE);
}
int len, n;
while(1){
n = recvfrom(sockfd, (char *)buffer, MAXLINE,
0, ( struct sockaddr *) &cliaddr,
&len);
printf("Client : %s\n", buffer);
bzero(buffer,sizeof(buffer));
sendto(sockfd, (const char *)hello, strlen(hello),
0, (const struct sockaddr *) &cliaddr,
len);
}
return 0;
}
客户:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define PORT 8080
#define MAXLINE 1024
// Driver code
int main() {
int sockfd;
char buffer[MAXLINE];
char *hello = "PING";
char *pocketLoss = "Pocket Loss";
struct sockaddr_in servaddr;
int worked = 0;
int notWorked = 0;
// Creating socket file descriptor
if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
memset(&servaddr, 0, sizeof(servaddr));
// Filling server information
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(PORT);
servaddr.sin_addr.s_addr = INADDR_ANY;
int n, len;
int counter = 0;
while(1){
if(counter%3 != 0){
sendto(sockfd, (const char *)hello, strlen(hello),
0, (const struct sockaddr *) &servaddr,
sizeof(servaddr));
sleep(2);
worked = worked + 1;
}else{
sendto(sockfd, (const char *)pocketLoss, strlen(pocketLoss),
0, (const struct sockaddr *) &servaddr,
sizeof(servaddr));
sleep(2);
notWorked = notWorked + 1;
}
counter = counter + 1;
printf("STTTILL");
n = recvfrom(sockfd, buffer, MAXLINE, 0, NULL, NULL);
}
printf("%d %d\n",worked,notWorked);
buffer[n] = '\0';
printf("Server : %s\n", buffer);
close(sockfd);
return 0;
}