为什么我只能发送txt文件而不能用别的类型的文件,别的类型的文件就是乱码呢 TCP套接字传送

armacd 2011-05-03 04:07:21
为什么我只能发送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"));
}


}


}

}
...全文
63 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
向立天 2011-05-21
  • 打赏
  • 举报
回复
您好
我是本版版主
此帖已多日无人关注
请您及时结帖
如您认为问题没有解决可按无满意结帖处理
另外本版设置了疑难问题汇总帖
并已在版面置顶
相关规定其帖子中有说明
您可以根据规定提交您帖子的链接
如您目前不想结帖只需回帖说明
我们会删除此结帖通知

见此回复三日内无回应
我们将强制结帖
相关规定详见界面界面版关于版主结帖工作的具体办法
xiaopoy 2011-05-03
  • 打赏
  • 举报
回复
我想到的有一个问题:
可能是recv收到的数据不是sd大小的 /:^] 判断下,然后继续recv直到得到了足够sd大小的数据?

15,979

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 界面
社区管理员
  • 界面
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧