我在一个CSocket类型的对象的OnReceive()事件中用到下列代码,可在运行时,一有数据发过来就出错。其实当结构FileInfor中不包含CString类时就没有问题,
一旦包含CString类型的变量就有问题。发送数据的那端的STRUCT结构是相同的,
我用它来保存一些文件的信息。
void FileSocket::OnReceive(int nErrorCode)
{
// TODO: Add your specialized code here and/or call the base class
struct FileInfor
{
CString FileName;CString FileExtra;
UINT FileSize;bool Accept;
} TempFile;
Receive(&TempFile,sizeof(FileInfor));
CFileDialog Dlg(false);
CString tempFilter;
tempFilter=
TempFile.FileExtra+"文件 (*."+TempFile.FileExtra+")\0*."+TempFile.FileExtra+"\0所有文件 (*.*)\0*.*\0\0";
Dlg.m_ofn.lpstrFilter=TEXT(tempFilter);
UINT nID=Dlg.DoModal();
CString Path;
Path=Dlg.GetPathName();
CFile theFile;
theFile.Open(Path,CFile::modeCreate|CFile::modeWrite|CFile::typeBinary);
TempFile.Accept=true;
Send(&TempFile,sizeof(FileInfor));
byte* pBuff=new byte[1024];
UINT Received=0;
UINT temp=0;
while(Received<TempFile.FileSize)
{ temp=0;
temp=Receive(pBuff, 1024);
theFile.Write(pBuff,temp);
Received+=temp;
}theFile.Close(); delete pBuff;
AfxMessageBox("文件接收完毕!",MB_OK+MB_ICONINFORMATION);
}
CSocket::OnReceive(nErrorCode);}
一旦包含CString类型的变量就有问题。发送数据的那端的STRUCT结构是相同的,
我用它来保存一些文件的信息。
void FileSocket::OnReceive(int nErrorCode)
{
// TODO: Add your specialized code here and/or call the base class
struct FileInfor
{
CString FileName;CString FileExtra;
UINT FileSize;bool Accept;
} TempFile;
Receive(&TempFile,sizeof(FileInfor));
CFileDialog Dlg(false);
CString tempFilter;
tempFilter=
TempFile.FileExtra+"文件 (*."+TempFile.FileExtra+")\0*."+TempFile.FileExtra+"\0所有文件 (*.*)\0*.*\0\0";
Dlg.m_ofn.lpstrFilter=TEXT(tempFilter);
UINT nID=Dlg.DoModal();
CString Path;
Path=Dlg.GetPathName();
CFile theFile;
theFile.Open(Path,CFile::modeCreate|CFile::modeWrite|CFile::typeBinary);
TempFile.Accept=true;
Send(&TempFile,sizeof(FileInfor));
byte* pBuff=new byte[1024];
UINT Received=0;
UINT temp=0;
while(Received<TempFile.FileSize)
{ temp=0;
temp=Receive(pBuff, 1024);
theFile.Write(pBuff,temp);
Received+=temp;
}theFile.Close(); delete pBuff;
AfxMessageBox("文件接收完毕!",MB_OK+MB_ICONINFORMATION);
}
CSocket::OnReceive(nErrorCode);}
建议用char的数组
4+4+4+1=13个字节
必须用char[]
char* mybuff=new char[MAX_PATH];
for(int i=0;i<MAX_PATH&&i<FileName.GetLength();i++)
mybuff[i]=FileName[i];
mybuff[i]='\0';
...delete []mybuff;
比如:
OnReceive()
{ CString m_Message;
ar>>m_Message;
....
}