请教接收网络文件?
请问下面的函数为什么有时可以下载文件,有时候又不能下载呢?
当然都是从HTTP,80端口下载的
char buff[512];
CString s;
WSADATA wsaData;
struct hostent *hp;
unsigned int addr;
struct sockaddr_in server;
CString servername;
CString filepath;
CString filename;
ParseURL(m_url,servername,filepath,filename);
int wsaret=WSAStartup(0x101,&wsaData);
if(wsaret)
{
s.Format("load socket dll failed!");
m_list.AddString(s);
return;
}
s.Format("Initialized WinSock");
m_list.AddString(s);
SOCKET conn;
conn=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(conn==INVALID_SOCKET)
{
s.Format("create socket failed!");
m_list.AddString(s);
return;
}
s.Format("SOCKET created");
m_list.AddString(s);
if(inet_addr(servername)==INADDR_NONE)
{
hp=gethostbyname(servername);
}
else
{
addr=inet_addr(servername);
hp=gethostbyaddr((char*)&addr,sizeof(addr),AF_INET);
}
if(hp==NULL)
{
s.Format("gethostbyname or gethostbyaddr failed!");
m_list.AddString(s);
closesocket(conn);
return;
}
s.Format("hostname/ipaddress resolved");
m_list.AddString(s);
server.sin_addr.s_addr=*((unsigned long*)hp->h_addr);
server.sin_family=AF_INET;
server.sin_port=htons(80);
if(connect(conn,(struct sockaddr*)&server,sizeof(server)))
{
s.Format("connect server failed!");
m_list.AddString(s);
closesocket(conn);
return;
}
s.Format("Connected to server :- %s",servername);
m_list.AddString(s);
sprintf(buff,"GET %s\r\n\r\n",filepath);
send(conn,buff,strlen(buff),0);
s.Format("sending command :- GET %s to server",filepath);
m_list.AddString(s);
CFile f;
int y;
CString fname="c:\\";
fname+=filename;
f.Open(fname,CFile::modeCreate | CFile::modeWrite);
s.Format("starting to receive file");
m_list.AddString(s);
int x=0;
while(y=recv(conn,buff,512,0))
{
f.Write(buff,y);
x=x+y;
}
f.Close();
s.Format("file length are %d",x);
m_list.AddString(s);
s.Format("File downloaded and saved :- %s",fname);
m_list.AddString(s);
closesocket(conn);
s.Format("SOCKET closed");
m_list.AddString(s);
WSACleanup();
s.Format("De-Initialized WinSock");
m_list.AddString(s);
问题点数:0、回复次数:4Top
1 楼xdxycx(何凡)回复于 2004-09-03 21:32:54 得分 0
那位大哥帮我看一下啊
给点提示啊Top
2 楼PiggyXP(【小猪】技术太差没脸上班,只好去念Ph.D了-_-b)回复于 2004-09-06 18:23:24 得分 0
是不是你得到的地址并非文件的真实下载地址呢?
你可以调试一下看看程序得到的文件链接直接在IE中是否可以下载?Top
3 楼oyljerry(【勇敢的心】→ ㊣提拉米苏√㊣)回复于 2004-09-06 19:23:22 得分 0
可能有些网络链接有转向,这样,你直接是下不到的Top
4 楼gdy119(夜风微凉)回复于 2004-09-17 22:00:03 得分 0
下载网络文件哪有你那么复杂?
看下面几行代码搞定:
CString GetFile(const char *url, const char *filename)
{
#define HTTPBUFLEN 512 // Size of HTTP Buffer...
char httpbuff[HTTPBUFLEN];
TCHAR szCause[255];
CString Cause;
Cause.Format("YES");
TRY
{
CInternetSession mysession;
CStdioFile *remotefile = mysession.OpenURL(url,1,INTERNET_FLAG_TRANSFER_BINARY|INTERNET_FLAG_RELOAD);
CFile myfile(filename, CFile::modeCreate|CFile::modeWrite|CFile::typeBinary);
while (int numbytes = remotefile->Read(httpbuff, HTTPBUFLEN))
myfile.Write(httpbuff, numbytes);
}
CATCH_ALL(error)
{
error->GetErrorMessage(szCause,254,NULL);
Cause.Format("%s",szCause);
}
END_CATCH_ALL;
return (Cause);
}
Top




