CSocket文件传输 分段传输的关键代码
分段传输的关键代码
struct
FILEINFO
{
int
fileLength;
//文件长度
char
fileName[100];
//文件名
};
|
服务器:
CFileDialog fileDialog(TRUE);
//选择文件
if
(fileDialog.DoModal()==IDOK)
{
CString filename = fileDialog.GetPathName();
//文件路径
CString name = fileDialog.GetFileName();
//文件名字
//发送文件
CFile file;
if
(file.Open(filename,CFile::modeReadWrite|CFile::typeBinary))
{
//打开文件
FILEINFO myFileInfo;
//文件结构
int
length = file.GetLength();
//获取文件的长度
m_CtrlProgressSend.SetRange32(0,length);
//设置进度条大小
m_CtrlProgressSend.SetPos(0);
myFileInfo.fileLength = length;
//赋值文件长度
strcpy
(myFileInfo.fileName,name.GetBuffer(name.GetLength()));
//拷贝文件名
name.ReleaseBuffer();
//释放buffer
int
iBufSize = 1024*5;
//设置文件缓冲区长度
int
iSize = iBufSize ;
//一次读取的长度
LPBYTE
pBuf=
new
BYTE
[iBufSize];
//定义缓冲区
m_sockClient.Send(&myFileInfo,
sizeof
(myFileInfo));
//发送文件头信息
//发送文件
int
iNnmByte;
UINT
uiTotal = 0 ;
while
(uiTotal<length)
{
if
(length-uiTotal < iBufSize)
//如果发送小于1024*5 ,则发送剩余那些....
iSize = length-uiTotal;
iSize = file.Read(pBuf,iSize);
//读取文件到缓冲区
iNnmByte = m_sockClient.Send(pBuf,iSize);
//发送剩下iSize-iCount的文件
uiTotal += iNnmByte;
//uiTotal总发送量
m_CtrlProgressSend.SetPos(uiTotal);
}
}
m_info.ReplaceSel(
"发送文件完毕\r\n"
);
file.Close();
}
m_CtrlProgressSend.SetPos(0);
}
|
客户端
FILEINFO myFileInfo;
m_client.Receive(&myFileInfo,
sizeof
(myFileInfo));
//接受文件信息
m_progress.SetRange32(0,myFileInfo.fileLength);
//设置进度
CString str;
str.Format(myFileInfo.fileName);
//文件名字
CFile file;
if
(file.Open(str,CFile::modeCreate|CFile::modeWrite))
{
UINT
uiLength;
uiLength = myFileInfo.fileLength ;
//文件长度
int
iBufSize = 1024*5;
int
iSize = iBufSize ;
LPBYTE
pBuf =
new
BYTE
[iBufSize];
int
iNumByte;
UINT
uiTotal = 0 ;
while
(uiTotal < uiLength)
{
if
(uiLength-uiTotal<iBufSize)
iSize = uiLength - uiTotal ;
iNumByte = m_client.Receive(pBuf,iSize);
file.Write(pBuf,iNumByte);
//写入文件
uiTotal+=iNumByte;
m_progress.SetPos(uiTotal);
}
if
(pBuf)
{
delete
[] pBuf;
pBuf = NULL;
}
}
file.Close();
m_info.ReplaceSel(
"接受文件成功\r\n"
);
m_progress.SetPos(0);
|