高手来看看代码,关于socket的。。。。。。。。
西山小月 2004-03-09 10:35:01 客户端向服务端方发送文件1.txt。
发送接收文件信息都显示成功,但是发送和接收文件总是显示失败,why??????????????????????????????????????????????????
客户端:
AfxSocketInit(NULL);
m_psockClient=new CClientSocket();
if(!m_psockClient->Create(1234))
{
delete m_psockClient;
m_psockClient=NULL;
AfxMessageBox("打开端口错误!");
return ;
}
if(!m_psockClient->Connect(strAddress, 9600))
{
delete m_psockClient;
m_psockClient = NULL;
AfxMessageBox("连接错误!");
return;
}
CSocket senSo;
FILEINFO myFileInfo;
m_psockClient->Init();
m_strPath="c:\\1.txt";
//打开文件
CFile file;
file.Open("c:\\1.txt", CFile::modeRead);
//获取文件大小
m_dwFileSize=file.GetLength();
m_strFileSize.Format("%ld 字节", m_dwFileSize);
myFileInfo.fileLength=file.GetLength();
strcpy(myFileInfo.fileName,file.GetFileName());
senSo.Send(&myFileInfo,sizeof(myFileInfo));
AfxMessageBox("发送文件信息成功");
int nSize = 0, nLen = 0;
DWORD dwCount = 0;
char buf[BLOCKSIZE] = {0};
file.Seek(0, CFile::begin);
//开始传送文件
AfxMessageBox("开始传送文件");
while(dwCount<m_dwFileSize)
{
//一次读取BLOCKSIZE大小的文件内容
nLen = file.Read(buf, BLOCKSIZE);
if(nLen == 0)
break;
//发送文件内容
nSize = senSo.Send(buf, nLen);
dwCount += nSize;
CString strTransfersSize;
strTransfersSize.Format("%ld 字节", dwCount);
}
//关闭文件
file.Close();
//关闭套接字
senSo.Close();
delete m_psockClient;
if(m_dwFileSize == dwCount)
AfxMessageBox(_T("文件发送成功"));
else
AfxMessageBox(_T("文件发送失败"));
}
服务端:
AfxSocketInit(NULL);
//创建套接字
CSocket sockSrvr;
if(!sockSrvr.Create(9600))
{
AfxMessageBox("文件服务器启动失败1");
return -1;
}
//开始监听
if(!sockSrvr.Listen())
{
AfxMessageBox("文件服务器启动失败2");
return -1;
}
//接受连接
CSocket recSo;
if(!sockSrvr.Accept(recSo))
{
AfxMessageBox("连接错误");
return -1;
}
sockSrvr.Close();
FILEINFO myFileInfo;
recSo.Receive(&myFileInfo,sizeof(FILEINFO));
int fileLength=myFileInfo.fileLength;
CString strfileName,strfileLength;
strfileName.Format(myFileInfo.fileName);
m_strPath=strfileName;
m_dwFileSize=fileLength;
strfileLength.Format("%f",myFileInfo.fileLength/1024.0);
AfxMessageBox("接收信息成功");
//接收文件
int nSize = 0;
DWORD dwCount = 0;
char buf[BLOCKSIZE] = {0};
//创建一个文件
CFile file(m_strPath, CFile::modeCreate|CFile::modeWrite);
AfxMessageBox("开始接收文件");
//开始接收文件
while(dwCount<m_dwFileSize)
{
//每次接收BLOCKSIZE大小的文件内容
nSize = recSo.Receive(buf, BLOCKSIZE);
if(nSize == 0)
break;
//将接收到的文件写到新建的文件中去
file.Write(buf, nSize);
dwCount += nSize;
CString strTransfersSize;
strTransfersSize.Format("%ld 字节", dwCount);
}
//关闭文件
file.Close();
//关闭套接字
recSo.Close();
if(m_dwFileSize==dwCount)
AfxMessageBox(_T("文件接收成功"));
else
AfxMessageBox(_T("文件接收失败"));
return 0;
}