编辑:老实说,我不知道错误发生在哪里,所以我将添加大部分相关代码,不确定这是否有帮助
所以基本上我有两个基本的服务器和客户端进程。用户指定一个命令,客户端进程然后将消息的长度发送给服务器,服务器执行命令并返回响应的消息长度。
这在第一个命令上效果很好(我连续尝试了两个 ls -la),第一个命令的值为 1028(正确的值),第二个命令的值为 1685223288(在客户端)不正确
使用以下代码完成写入:
server_handler() {
char str[5000];
char * token = NULL;
unsigned long totalSize = 0;
str[0] = "\0";
totalSize = htonl(totalSize); // Correct size already calculate
if((result = write(clientFD, (char *) &totalSize, sizeof(totalSize)) < 0))
{
printf("Failed sending size to client\n");
exit(-1);
}
//Here the server starts sending the results to the client
token = strtok(str, "\n"); // str array contains the results
while(token != NULL)
{
token[strlen(token)] = '\n';
write(clientFD, token, strlen(token));
token = strtok(NULL, "\n);
}
读取在客户端进程中通过以下方式完成:
static void handle_reply()
{
char * revBuf = 0;
unsigned long int bytesRead = 0;
unsigned long bufferlen = 0;
while(1)
{
result = read(socketFD, (char *) &bufferlen, sizeof(bufferlen));
bufferlen = ntohl(bufferlen);
recvBuf = malloc(bufferlen);
//Here client starts reading results
while(bytesread < bufferlen)
{
result = read(socketFD, recvBuf, bufferlen);
printf("recvBuf: %s\n", recvBuf);
bytesRead = strlen(recvBuf) + bytesRead;
}
free(recvBuf);
bufferlen = 0;
client_handler(); //calls Function that asks for new command
}
}
我的问题:为什么我在第一个命令之后收到错误的值?, 我已经验证了在两种情况下,totalSize 在服务器端都具有正确的值并打印。写/读一定有问题?
我还在服务器上打印了 htonl(totalSize),它是 67371008。但是在客户端收到的值是 ntohl 之前的 2021093988。