我正在尝试解决一个奇怪的 C 编程问题。
我在客户端程序上输入 URL,然后将该 URL 传输到服务器程序。唯一的问题是,当服务器程序接收到 URL 时,它缺少前两个字符。因此,如果 URL 是http://www.google.com,则服务器报告接收的是“tp://www.google.com”。
奇怪的是,这不是部分发送问题。我正在检查发送的字节数,它声称发送了整个消息。问题是在接收端它只是声称它正在获取一小部分数据。接收方报告它收到的消息长度为-2。这是接收端的代码:
printf("%s \n", "Connected. Receive length of URL to wget.");
if ((messageSize = recv(acceptDescriptor, &urlLength, sizeof (int), 0)) == -1) {
perror("recv URL length");
exit(1);
}
urlSizeInt = atoi(urlLength);
char url[urlSizeInt];
printf("%s %d \n", "urlSizeInt: ", urlSizeInt);
printf("%s \n", "Receive URL to wget.");
if((messageSize = recv(acceptDescriptor, &url, 13, 0)) == -1) {
perror("recv URL");
exit(1);
}
发送代码:
printf("%s \n", "Connected");
//connected to first stepping stone in the chain.
//transfer the length of the URL
if (send(socketDescriptor, urlLengthStr, strlen(urlLengthStr), 0) == -1){
perror("send URL Length");
exit(0);
}
//transfer the URL
printf("%s %d \n", "strenlen(url): ",strlen(url));
printf("%s %s \n", "url: ",url);
int sent;
int totalSent=0;
if((sent=send(socketDescriptor, url, strlen(url), 0))==-1){
perror("send URL");
exit(0);
}
printf("%s %d \n", "sent: ",sent);
Send Output:
Connected
strenlen(url): 13
url: http://www.cs
sent: 13
Receive Output:
Connected. Receive length of URL to wget.
urlSizeInt: 13
Receive URL to wget.
messageSize: 11
URL Received: tp://www.cs
将长度编码为用于发送的字符的代码:
char* url = "http://www.cs";
int urlLength = strlen(url);
char* urlLengthStr;
sprintf(urlLengthStr, "%d", urlLength);