用C++和socket来获取网页信息 如何实现?有代码最好 5

 我来答
GYC_OYYL
推荐于2016-06-06 · TA获得超过248个赞
知道答主
回答量:52
采纳率:100%
帮助的人:68.9万
展开全部
Linux版本的:

/*
* URLDownload.h
*
* Created on: 2010-9-14
*/

#ifndef URL_DOWNLOAD_H
#define URL_DOWNLOAD_H

#include <cstring>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
using std::string;

//return type
#define HTTP_SUCCESS 1
#define HTTP_UNKNOW_HOST 2
#define HTTP_SOCKET_ERROR 3
#define HTTP_CONNECT_ERROR 4
#define HTTP_WRITE_ERROR 5
#define HTTP_SELECT_ERROR 6
#define HTTP_BAD_HEADER 7
#define HTTP_READ_ERROR 8
#define HTTP_UNKNOWN_ERROR 0

/**
* 根据host、port、path下载网页,成功则返回HTTP_SUCCESS
* host为主机名,ip或者域名
* port为端口号
* path为访问资源的路径
* body为最终获取的网页内容
*/
int downloadURL(const char *host, unsigned short port, const char *path, string &body)
{

int sock;
struct sockaddr_in sin;

//get host by name
struct hostent *he=gethostbyname(host);
if(!he)
{
return HTTP_UNKNOW_HOST;
}
sin.sin_family=he->h_addrtype;
sin.sin_port = htons(port);
sin.sin_addr.s_addr=((unsigned long*)(he->h_addr_list[0]))[0];

//create socket
if( (sock=socket(AF_INET,SOCK_STREAM,0))<0 )
{
return HTTP_SOCKET_ERROR;
}
//connect to the server
if(connect(sock,(struct sockaddr*)&sin,sizeof(sin))<0)
{
close(sock);
return HTTP_CONNECT_ERROR;
}

char str[4096];
sprintf(str, "GET %s HTTP/1.0\r\nHost:%s\r\nUser-Agent:Mozilla/4.0\r\n\r\n",
path, host);
//send http request
if(write(sock,str,strlen(str))<0)
{
close(sock);
return HTTP_WRITE_ERROR;
}

fd_set rfds;
struct timeval tv;

FD_ZERO(&rfds);
FD_SET(sock,&rfds);

tv.tv_sec=3;//m_nSecs;
tv.tv_usec=0;

if(!select(sock+1,&rfds,NULL,NULL,&tv))
{
close(sock);
return HTTP_SELECT_ERROR;
}

if(FD_ISSET(sock,&rfds))
{
int len=1024*4;
string content;
int rv=0;
char buf[len+1];
//read data
while( (rv=read(sock,buf,len)) )
{
buf[rv] = 0 ;
content += buf ;
}
close(sock);

//
if(!content.empty())
{
if( content.find("200") >= content.find("\n") )
{
return HTTP_UNKNOWN_ERROR;
}

int start = 0;
if( start = content.find("\r\n\r\n") )
{
body.append( content.c_str() + start + 4 );
}else if( start = content.find("\n\n") )
{
body.append( content.c_str() + start + 2 );
} else
{
return HTTP_BAD_HEADER;
}

return HTTP_SUCCESS;
}

return HTTP_READ_ERROR ;

}
close(sock);
return HTTP_UNKNOWN_ERROR;
}

/**
* 根据url下载网页,成功则返回HTTP_SUCCESS
* url为网页地址
* body为获取的网页内容
*/
int downloadURL(string &url, string &body)
{
int end = url.find("/");
string host = url.substr(0, end);
string path = url.substr(end);

return downloadURL(host.c_str(), 80, path.c_str(), body);
}

#endif
eweqtem
2011-01-10 · TA获得超过4873个赞
知道小有建树答主
回答量:886
采纳率:66%
帮助的人:274万
展开全部
Server.cpp 内容如下:

#include "stdafx.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// The one and only application object

CWinApp theApp;

using namespace std;

#define PORT 34000 /// Select any free port you wish

void SendFile(LPCTSTR strFilename)
{
AfxSocketInit(NULL);
CSocket sockSrvr;
sockSrvr.Create(PORT); // Creates our server socket
sockSrvr.Listen(); // Start listening for the client at PORT
CSocket sockRecv;
sockSrvr.Accept(sockRecv); // Use another CSocket to accept the connection

CFile myFile;
if(!myFile.Open(strFilename, CFile::modeRead | CFile::typeBinary))
return;

int myFileLength = myFile.GetLength(); // Going to send the correct File Size

sockRecv.Send(&myFileLength, 4); // 4 bytes long

byte* data = new byte[myFileLength];

myFile.Read(data, myFileLength);

//1024

int iRet ;
iRet = sockRecv.Send(data, myFileLength); //Send the whole thing now
cout << "Ret = " << iRet << endl;

cout << "send file over!" << endl;

myFile.Close();
delete data;

sockRecv.Close();
}

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;

// initialize MFC and print and error on failure
cout << "init send file" << endl;
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
cerr << _T("Fatal Error: MFC initialization failed") << endl;
nRetCode = 1;
}
else
{
//SendFile("C:\\autoexec.bat");
cout << "send file" << endl;
SendFile("I:\\程序.txt");
}

getchar();

return nRetCode;
}

client.cpp 代码如下:
#include "stdafx.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// The one and only application object

CWinApp theApp;

using namespace std;
#define PORT 34000

void GetFile(LPCTSTR strFilename)
{
AfxSocketInit(NULL);
CSocket sockClient;
sockClient.Create();
sockClient.Connect("127.0.0.1", PORT); // "127.0.0.1" is the IP to your server, same port

int dataLength;
sockClient.Receive(&dataLength, 4); //Now we get the File Size first

byte* data = new byte[dataLength];
sockClient.Receive(data, dataLength); //Get the whole thing

CFile destFile(strFilename, CFile::modeCreate | CFile::modeWrite | CFile::typeBinary);

destFile.Write(data, dataLength); // Write it

destFile.Close();

cout << "Recive file over!" << endl;

delete data;
sockClient.Close();

}

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;

// initialize MFC and print and error on failure
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
cerr << _T("Fatal Error: MFC initialization failed") << endl;
nRetCode = 1;
}
else
cout << "recive file start " << endl;
GetFile("I:\\程序copy.txt");
return nRetCode;
}

百度不支持附件,不然可以把工程给你。
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式