我正在开发一个网络软件作为大学考试的一部分。软件快完成了,但实际上我正在完成并发部分(使用 fork())。我的需要是在客户端和服务器之间交换这两条消息作为握手。这里是一个例子:PING:3506:DOWNLOAD PONG:5605
这是我处理这些消息的方法:在客户端,即发送 PING:3506:DOWNLOAD 的主机,我写道
int *childLocalPort;
childLocalPort = malloc(sizeof(int));
childLocalPort[0] = (SERV_PORT_OFFSET + getPort(&portArray, &pidArray, &arrayCounter, cpid));
char *pingProcedureString;
pingProcedureString = malloc(30*sizeof(char));
strcpy(pingProcedureString, "PING:");
char *itoaPortBuffer;
itoaPortBuffer = malloc(6*sizeof(char));
itoa((childLocalPort[0]), itoaPortBuffer, 10);
strcat(pingProcedureString, itoaPortBuffer);
strcat(pingProcedureString, ":DOWNLOAD");
if (sendto(sockfd, pingProcedureString, strlen(pingProcedureString), 0, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
{
perror("errore in sendto1");
exit(1);
}
free(itoaPortBuffer);
free(pingProcedureString);
n = recvfrom(sockfd, buff, MAXLINE, 0, NULL, NULL);
buff[n] = 0;
if(strcmp(buff,"PONG"))
{
int *childRemotePort;
childRemotePort = malloc(sizeof(int));
strtok(buff, ":");
childRemotePort[0] = ntohs(strtok(NULL, ":"));
printf("Remote port is %d\n", childRemotePort[0]);
close(pipeLocalPort[0]); /* Close unused read end */
write(pipeLocalPort[1], childLocalPort, sizeof(int)
close(pipeLocalPort[1]); /* Reader will see EOF */
close(pipeRemotePort[0]);
write(pipeRemotePort[1], childRemotePort, sizeof(int));
close(pipeRemotePort[1]);
}
在服务器端,即发送 PONG:5605 的主机,我写了
if ((n > 0) && strcmp(recvline,"PING"))
{
int *childRemotePort;
childRemotePort = malloc(sizeof(int));
strtok(recvline, ":");
char *buffTemp;
buffTemp = calloc(5, sizeof(char));
strcpy(buffTemp,strtok(NULL, ":"));
childRemotePort[0] = ntohs(atoi(buffTemp));
strtok(recvline, ":");
printf("Remote child client port is: %d\n", childRemotePort[0]);
}
如您所见,PONG 部分丢失了,因为我想专注于第一个非工作部分。服务器正确接收(正如我从 Wireshark 看到的)消息 PING:3506:DOWNLOAD,但他告诉我他收到的是 19476 而不是 3506,这不是真的。我还注意到,如果我尝试发送数字消息而不将它们转换为网络字节顺序,情况会变得更糟。很多天我都在与这个作斗争,我不知道该怎么想了。