我目前有一个UDP Client程序,用于接收来自服务器的数据包,将每个数据包添加到完整的消息char数组中,直到没有剩余。
我现在有一个分配,在这里我必须用传输不足的数据包启动服务器,然后将它们按客户端的顺序排序。
虽然我知道数据包号存储在buf标记的前两个字符中,但我只是停留在按顺序编写它们的最佳方法上。
我只需要等到所有数据包都写上带有标签的标签,重新排序然后再删除标签?还是有更简单的方法可以解决这个问题呢?
参数和变量:
//This char pointer is used to remove the tag from the start of each message
//Buf is set equal to this then this is set equal to the location of the char array
//where the data starts
char *buf_pointer;
//Used to hold the full poem
char fullMessage[MAXBUF];
//Used to hold the name of incoming file
char title[MAXBUF];
char *titlePtr;
//Boolean value to stop the loop when the full message is recieved
bool continue_loop = true;
//Boolean value to determine if it is the first iteration of the loop
bool first_time = true;
循环接收和写入数据包:
//While loop to repeat recvfrom until there is no data left
while(continue_loop){
retval = select(sockfd+1, &rfds, NULL, NULL, &tv);
//An error occured with select
if (retval == -1) perror("select()");
//Data is available from sockfd
else if (retval){
//The first data packet is formatted differently, and thus
//will need to be handled differently
if(first_time){
nread = recvfrom(sockfd,title,MAXBUF,0,NULL,NULL);
if (nread < 0) {
perror("CLIENT: Problem in recvfrom");
exit(1);
}
else {
titlePtr = title;
titlePtr = &titlePtr[8]; //Removing tag from the first packet
first_time = false;
}
}
else{
nread = recvfrom(sockfd,buf,MAXBUF,0,NULL,NULL);
if (nread < 0) {
perror("CLIENT: Problem in recvfrom");
exit(1);
}
else {
totalBytes += nread; //Incrementing total number of bytes
buf_pointer = buf; //Setting received data to char pointer
buf_pointer = &buf_pointer[6]; //Removing tag from packet
strcat(fullMessage, buf_pointer); //Adding message to full char array
}
}
}
//No messages read for 1 second
else continue_loop = false;
}
我的库尔卡尼男人让你感到难过。