使用 TCP 从客户端向服务器发送字节的问题
我的 send() 和 recv() 看起来像这样:
int Send(const char* buffer, int size)
{
cout << "SIZE: " << size << endl;
int offset;
while(offset < size)
{
int n = ::send(getSocket(), buffer + offset, size - offset, 0);
if(n == SOCKET_ERROR)
{
break;
}
offset += n;
if(offset != size)
{
Sleep(1);
}
}
return offset;
}
int Recv(char* buffer, int size)
{
int n = ::recv(getSocket(), buffer, size, 0);
if(n == SOCKET_ERROR)
{
cout << "Error receiving data" << endl;
}
if(n == 0)
{
cout << "Remote host closed connection" << endl;
}
return n;
}
但我的输出显示发送了很多字节,这对我来说似乎很奇怪:
Received from client: 669
Sent to web server: 3990336
所以它应该发送 669 个字节,那么它从哪里得到 3990336 ?这是某种错误还是?
谢谢。
My send() and recv() looks like this:
int Send(const char* buffer, int size)
{
cout << "SIZE: " << size << endl;
int offset;
while(offset < size)
{
int n = ::send(getSocket(), buffer + offset, size - offset, 0);
if(n == SOCKET_ERROR)
{
break;
}
offset += n;
if(offset != size)
{
Sleep(1);
}
}
return offset;
}
int Recv(char* buffer, int size)
{
int n = ::recv(getSocket(), buffer, size, 0);
if(n == SOCKET_ERROR)
{
cout << "Error receiving data" << endl;
}
if(n == 0)
{
cout << "Remote host closed connection" << endl;
}
return n;
}
But my output show kind of many bytes sent that seems strange to me:
Received from client: 669
Sent to web server: 3990336
So it should supose to sent 669 bytes, so from where did it get 3990336 ? It is some kind of error or ?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您是否注意到
int offset;
没有初始化?Did you notice that
int offset;
is not initialize ?offset
初始化为零。否则它可以是任何随机值。Sleep
,因为send
调用被阻塞。offset
with zero. Otherwise it could be any random value.Sleep
assend
call is blocking.也许这只是您的(精简的?)示例代码,但您从未真正初始化
offset
。它可能具有任何值,例如-5000,并且将导致循环发送5669 字节。Maybe it's just your (stripped down?) example code, but you never actually initialize
offset
. It might have any value, e.g. -5000 and will cause the loop to send 5669 bytes.