为什么我只能发送txt文件而不能用别的类型的文件,别的类型的文件就是乱码呢 TCP套接字传送
为什么我只能发送txt文件而不能用别的类型的文件,别的类型的文件就是乱码呢 TCP套接字传送
数据包结构体为:#define filesize 4096
struct receive_data
{
short start_flag;
char cmd;
int length;
BYTE msg[filesize];
BYTE extname[4];
};
发送端:
struct send_data sd;
DWORD dwRead;
CFile m_file(m_strPath,CFile::modeRead|CFile::typeBinary);
for (int i=0;i<4;i++)
{
sd.extname[i]=0;
}
CString str1;
int beginpos=m_strPath.ReverseFind('.');
int endpos=m_strPath.GetLength();
str1=m_strPath.Mid(beginpos,endpos-beginpos);
int len = str1.GetLength();
char * temp = str1.GetBuffer(len);
int lenTemp = sizeof(sd.extname);
strncpy((char*)sd.extname,temp,lenTemp);
str1.ReleaseBuffer();
sd.start_flag=0xff;
sd.cmd=0x4;
sd.length=m_file.GetLength();
int count=sd.length/4096;
if (sd.length>4096)
{
sd.start_flag=0x99;
}
for (i=0;i<4096;i++)
{
sd.msg[i]=' ';
}
send(msgsock,(char*)&sd,sizeof(sd),0);
do
{
m_file.Read(sd.msg, 4096);
send(msgsock,(char *)&sd,sizeof(sd),0);
count--;
}
while (count >= 0);
接受端:
while(s!=SOCKET_ERROR)
{
s=recv(dlg->clisock,(char*)&rd,sizeof(rd),0);
if (rd.cmd==0x7) //接消息
{
if (s!=SOCKET_ERROR)
dlg->m_listInfo.InsertItem(dlg->count++,(char *)rd.msg);
dlg->m_listInfo.Scroll(size);
for (int i=0;i<strlen((char *)rd.msg);i++)
{
rd.msg[i]=' ';
}
}
else if (rd.cmd==0x4)//接文件
{
if(IDOK == AfxMessageBox(_T("您收到一个文件请确定是否接收?"), MB_OKCANCEL | MB_ICONQUESTION))
{
CFileDialog fileDlg(FALSE);
if(IDOK == fileDlg.DoModal())
{
CFile destFile(fileDlg.GetPathName()+rd.extname,CFile::modeCreate | CFile::modeWrite | CFile::typeBinary);
int mod;
UINT dwRead ;
int count=rd.length/4096; if (rd.length>=4096)
{
mod=rd.length%4096;
}
else
{
mod=rd.length;
}
if (rd.start_flag==0x99)
{
do
{
byte* data = new byte[4096];
memset(data,0,4096);
dwRead=recv(dlg->clisock,(char*)&rd,sizeof(rd),0);
memcpy(data,rd.msg,dwRead);
destFile.Write(data, dwRead);
count--;
}while(count>0);
recv(dlg->clisock,(char*)&rd,sizeof(rd),0);
destFile.Write(rd.msg, mod);
}
else
{
recv(dlg->clisock,(char*)&rd,sizeof(rd),0);
destFile.Write(rd.msg, mod);
}
destFile.Close();
AfxMessageBox("接收完毕!");
for (int i=0;i<strlen((char *)rd.msg);i++)
{
rd.msg[i]=' ';
}
}
else
{
AfxMessageBox(_T("CANCEL"));
}
}
}
}