关于Soket接受数据的问题,请高手看过来(100分)

  • 主题发起人 主题发起人 neteye00
  • 开始时间 开始时间
N

neteye00

Unregistered / Unconfirmed
GUEST, unregistred user!
我现在在做C/S模式下的TCP通信程序,我用的是C++Builder5中ClientSocket,
关键代码实现如下:

void __fastcall TFrmMain::CSocketRead(TObject *Sender,
TCustomWinSocket *Socket)
{

char *RevMsg=NULL,*PkgBody=NULL;
int PkgLen=0,FLen=0;

char PkgHead[SHEAD_LEN],MsgLen[SPKGLEN_LEN+1],PkgEnd[SEND_LEN];//,msgstr[4096];

memset( PkgHead,0,SHEAD_LEN );
memset( PkgEnd,0,SEND_LEN );
memset(MsgLen,0,SPKGLEN_LEN+1);
Socket->Lock();
memset(PkgHead,0,SHEAD_LEN);

int rc = ::recv(Socket->SocketHandle, PkgHead, 4, MSG_PEEK);
if (rc >= 4 && memcmp(PkgHead,"HEAD",SHEAD_LEN))
{
//Socket->Unlock();
return;
}

Socket->ReceiveBuf(PkgHead,SHEAD_LEN);
if (memcmp(PkgHead,"HEAD",SHEAD_LEN)) //报文开始标志
{

//Socket->Unlock();
return ;
}
Socket->ReceiveBuf(MsgLen,SPKGLEN_LEN);

PkgLen = atoi(MsgLen); //报文实际长度


RevMsg = new char[PkgLen];
FLen = ReadMsg(RevMsg,PkgLen);


Socket->ReceiveBuf(PkgEnd,SEND_LEN);
if (memcmp(PkgEnd,"END",SEND_LEN))
{
//Socket->Unlock();
return;
}

memcpy(&PKGINFO,RevMsg,PkgLen);

PkgBody = new char[CONTENT_LEN-sizeof(TRANSFER_HEAD)];

FLen = CONTENT_LEN;

PkgLen = PkgLen - sizeof(TRANSFER_HEAD);

GetPkgBody((unsigned char *)PKGINFO.detail,PkgLen,(unsigned char *)PkgBody,&FLen);

AnalyzePackage(PkgBody); //分解报文,处理窗体

Socket->Unlock();
delete []RevMsg;
delete []PkgBody;

}
//---------------------------------------------------------------------------

int ReadMsg(char *buf,int msglen)
{
int iReaded, iLeft,iReadLen=0;

for( iLeft = msglen; iLeft > 0; )
{


if( ( iReaded = FrmMain->CSocket->Socket->ReceiveBuf(buf, iLeft )) >= 0 )
{
iLeft -= iReaded;
buf += iReaded;
iReadLen +=iReaded;
}
else
{
//return (-1);
//ShowMessage("ok");
//return iReadLen;
}
}
//return ( msglen - iLeft);

return iReadLen;
}
//--------------------------------------------------------------------------
请大家看看有什么问题。
 
后退
顶部