我正在用C写一个服务器-客户端程序,客户端以5个字节的形式向服务器发送命令:第一个字节是一个操作,接下来的4个字节是对其进行操作的关键.
服务器看起来像这样:
int nowread, key;
while(1)
{
char buffer[1024];
int alreadyread = 0;
do
{
nowread = read(socket,buffer+alreadyread,5-alreadyread);
alreadyread += nowread;
}
while((nowread > 0) && (5-alreadyread > 0));
if(nowread == -1 || nowread == 0)
{
printf("Error reading from client socket\n");
exit(1);
}
key = (((int)buffer[1])<<24 | ((int)buffer[2])<< 16 | ((int)buffer[3]) << 8 | ((int)buffer[4]) << 0);
printf("%d, key from server \n",key); // just for debugging
//DO COMMAND
我一直在通过让客户端发送 10 个命令来测试程序:
op: 1, num: 645110
op: 2, num: 419811
op: 0, num: 115300
op: 2, num: 792023
op: 2, num: 146624
op: 1, num: 842346
op: 1, num: 450778
op: 0, num: 550046
op: 1, num: 284186
op: 2, num: 691858
然后我从服务器获取:
-10, key from server
-29, key from server
-15772, key from server
-41, key from server
-64, key from server
-9622, key from server
-38, key from server
-98, key from server
284186, key from server
-110, key from server
如您所见,只有一个键匹配,这很奇怪(它们要么全部匹配,要么都不匹配)。我 100% 确定这是服务器端的问题,而不是客户端的问题。有谁知道是什么原因造成的?
提前致谢。
编辑: 这是发送数据的代码
uint32_t net_num = htonl(num);
int nsent = 0;
while (nsent < 4)
{
rc = write(sockfd,&net_num + nsent, 4 - nsent);
if (rc <= 0)
{
printf("error! write() failed: %s\n", strerror(errno));
break;
}
nsent += rc;
}
if (rc <= 0)
break;
最佳答案
您正在以错误的方向处理缓冲区。您还需要将其从网络字节转换回来。 ntohl ( ) 就是这样做的。
像这样:
uint32_t key;
uint32_t result;
key = ( uint32_t )(( buffer [ 1 ] << 0 ) |
( buffer [ 2 ] << 8 ) |
( buffer [ 3 ] << 16 ) |
( buffer [ 4 ] << 24 ));
result = ntohl ( key );
关于C:客户端和服务器之间的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30832122/