2 zhaowenjie988111 zhaowenjie988111 于 2014.06.02 15:40 提问

TCP 非阻塞套接字 发送文件数据会丢失

用以下函数将套接字设置为非阻塞套接字
bool setSockNoBlock(SOCKET s)
{
bool flg=true;
if (::ioctlsocket(s, FIONBIO, (unsigned long )&flg)==0)
{
cout<<"socket"< return true;
}
return false;
}
发送文件代码:
bool sendFile(SOCKET s,char *fileName)
{
CWGFILE wgSendFile;
char buf[WG_MAX_TCPBUF];
ZeroMemory(buf,WG_MAX_TCPBUF);
int len=0;
int fileLen=0;
int count=0;
double timeCount;
CTimer t;
if (wgSendFile.WG_FileOpen(fileName,WG_FILE_READ))
{
t.Start();
while((len=wgSendFile.WG_FileRead(buf))>0)
{
fileLen+=len;
send(s,buf,len,0);
/*Sleep(1);
/
// cout<<count<<":"<<len<<" ";
count++;
if (fileLen == wgSendFile.WG_FileLen())
{
timeCount = t.End();
cout<<"发送时间:"<<(double)(timeCount/1000.0)<<"S"<<endl;
cout<<"发送速度:"<<(double)(fileLen/1024.0/1024.0)/(timeCount/1000.0)<<"M/S"<<endl;
return wgSendFile.WG_FileClose(), true;
}
ZeroMemory(buf,WG_MAX_TCPBUF);
}
}
return false;
}

接收数据方代码:
do
{
nRet = recv(sockClient,buf,WG_MAX_TCPBUF,0);
if (nRet>0)
{
len+=nRet;
wgRecvFile.WG_FileWrite(buf,nRet);
ZeroMemory(buf,WG_MAX_TCPBUF);
//cout<<count<<":"<<nRet<<" ";
count ++;
if (len == 941473792 )//本应该接收的数据长度
{
cout<<"\n接受终于完了!"<<endl;
break;
}
}
if (nRet==0)
{
cout<<"\n服务器断开了,共接收数据:"<<len<<endl;
break;
}
} while (nRet!=0);

Csdn user default icon
上传中...
上传图片
插入图片