最近在做一个传输程序,不是很稳定?现把代码贴上来,希望高手可以给出一些指正!谢谢!

李海峡 李海峡 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
1.这是服务器接收线程函数
UINT ListenTcpThread(LPVOID lparam)
{
CSERVERDlg *pDlg=(CSERVERDlg *)lparam;

CSocket sockSrvr;
int createSucceed=sockSrvr.Create(pDlg->m_port);
if(createSucceed==0)
{
AfxMessageBox("创建服务错误!");
return -1;
}

int listenSucceed=sockSrvr.Listen(); //开始监听
if(listenSucceed==0)
{
AfxMessageBox("创建监听错误");
return -1;
}

CSocket recSo;
SOCKADDR_IN client;
int iAddrSize=sizeof(client);

int acceptSucceed=sockSrvr.Accept(recSo,(SOCKADDR *)&client,&iAddrSize); //接受连接并取得对方IP
if(acceptSucceed==0)
{
AfxMessageBox("接受客户端错误!");
return -1;
}
sockSrvr.Close();
/////////////////////判断发送的信息类型//////////////////////
char flag[2]={0};
if(recSo.Receive(flag,2)!=2)
{
AfxMessageBox("错误");

return -1;
}
pDlg->m_type=flag[0];

////////////////////////////////////////////////////////////

if(Flag==1) return 0;

pThreadLisen=::AfxBeginThread(ListenTcpThread,pDlg);
pDlg->ReceiveFileMsg(recSo,client);
return 0;

}

2.这是服务器端接收信息的函数:
int CSERVERDlg::ReceiveFileMsg(CSocket &recSo, SOCKADDR_IN &client)
{

bool iscon=true;
if(m_type=='F')
{

SaveYouFile(recSo,client);

}

if(m_type=='M')
{

char buff[1024]={0};
CString msg;
int ret=0;
for(;;)
{
ret=recSo.Receive(buff,1024);
if(ret <= 0 )
break;
msg+=buff;
}

CString strOut,strIn;
GetNamebyAddress(strIn,strOut);
CString youName;
youName.Format(inet_ntoa(client.sin_addr));
CString str=youName;

if(MySQL!=msg)
{
MySQL=msg;

iscon=true;

}else
{
iscon=false;

}

try
{

if(iscon)
{
m_list.SetTextColor(RGB(0,0,255));
m_list.InsertItem(0,str);
m_list.SetItemText(0,1,MySQL);
m_data->ExecuteSQL(MySQL);

}

}
catch(...)
{

}
}

recSo.Close();


return 0;
}

3.这是服务器端接收文件的函数
int CSERVERDlg::SaveYouFile(CSocket &recSo, SOCKADDR_IN &client)//接受文件
{

CString fname;

FILEINFO myFileInfo;

recSo.Receive(&myFileInfo,sizeof(FILEINFO));

int fileLength=myFileInfo.fileLength;//文件长度

CString strfileIp,strfileName,strfileLength;

strfileIp.Format(inet_ntoa(client.sin_addr));//发送者的IP地址
strfileName.Format(myFileInfo.fileName); //文件名
strfileLength.Format("%f",myFileInfo.fileLength/1024.0);

int strlen=strfileName.GetLength();
strlen-=19;

CString dirPath=strfileName;
dirPath=dirPath.Mid(0,strlen);

int i=0,j=0;
if(dirPath.Right(1)!="\\")dirPath+="\\";

try
{
while(i<dirPath.GetLength())
{ i=dirPath.Find("\\",j+1);
if(i==-1)i=dirPath.GetLength();
_mkdir(dirPath.Left(i).operator LPCTSTR());
j=i;

}
}catch(...)
{
}

strfileName=strfileName;

char buf[1024]={0};
int n=0; //接受的字节数 0表示结束
int temp=0;

try
{
CFile f(strfileName,CFile::modeCreate|CFile::modeWrite);//存文件

for(;;)
{
n=recSo.Receive(buf,1024); //接受
if(n <= 0) //0表示结束
break; //接受完毕
f.Write(buf,n);
temp+=n;

}
f.Close();
}catch(...)
{
}


if(temp==fileLength)
{
return 0;
}else
{
return -1;
}
}
...全文

相关推荐

评论 11
收藏 已收藏
分享
返回顶部
李海峡
网络编程 18,356 成员 64,161 内容