#include "ace/Log_Msg.h" // ACE_DEBUG的宏定义在这里.
#include "ace/OS.h"
#include "ace/CDR_Stream.h"
#include "ace/INET_Addr.h"
#include "ace/SOCK_Connector.h"
#include "ace/SOCK_Stream.h"
#include "ace/streams.h"
#include "ace/Log_Record.h"
#include <iostream>
unsigned long CDownloader::directDownload()
{
// http://p3.img.cctvpic.com/fmspic/2013/07/19/62f0a17c7ac74c679d47da4bd9ce0c8e-180.jpg
std::string strDomain = "vod.cntv.lxdns.com";
std::string strPath = "/flash/mp4video29/TMS/2013/07/19/62f0a17c7ac74c679d47da4bd9ce0c8e_h264818000nero_aac32-2.mp4";
// 从URL转换为IP
hostent* he = NULL;
if ( (he = ACE_OS::gethostbyname(strDomain.c_str())) == NULL)
{
ACE_ERROR_RETURN( (LM_ERROR, "%p\n", "ACE_OS::gethostbyname"), ACE_OS::last_error());
}
// 构造sockaddr_in结构.
struct sockaddr_in addr;
addr.sin_family = AF_INET;
memcpy(&addr.sin_addr, he->h_addr_list[0], he->h_length);
assert(INADDR_NONE != addr.sin_addr.s_addr);
addr.sin_port= htons(80);
// 初始化ACE结构.
int result;
ACE_INET_Addr svr_addr;
result = svr_addr.set(&addr, sizeof(sockaddr_in));
if (-1 == result)
{
ACE_ERROR_RETURN( (LM_ERROR, "%p\n", "build ACE_INET_Addr"), ACE_OS::last_error());
}
// 连接
ACE_SOCK_Stream strm;
ACE_SOCK_Connector connector;
if (connector.connect(strm, svr_addr) < 0)
{
ACE_ERROR_RETURN( (LM_ERROR, "%p\n", "ACE_SOCK_Connector.connect"), ACE_OS::last_error());
}
// 发Request
static const char headMethod[] = "HEAD ";
static const char getMethod[] = "GET ";
static const char keepAlive[] = "Connection: keep-alive \r\n";
static const char prot[] = " HTTP/1.1\r\n";
static const char acc[] = "Accept: text/html, application/xhtml+xml, application/xml;q=0.9,image/webp,*/*;q=0.8\r\n";
static const char lang[] = "Accept-Language: zh-cn,zh;q=0.8\r\n";
static const char enc[] = "Accept-Encoding: gzip, deflate, sdch\r\n";
static const char browser[] = "User-Agent: Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0) \r\n";
static const char host[] = "Host:";
static const char end[] = "\r\n\r\n";
std::string str = getMethod;
str += strPath.c_str();
str += prot;
str += acc;
str += lang;
str += enc;
str += browser;
str += host;
str += strDomain.c_str();
str += end;
ACE_OutputCDR request(const_cast<char*>(str.c_str()), str.size());
iovec iov[1];
iov[0].iov_base = request.begin()->rd_ptr();
iov[0].iov_len = str.size();
ssize_t sended = strm.sendv_n(iov, 1);
// 收Response
// 根据需要处理.这只是个示例.
const int bs = 1024*10;
ACE_Message_Block* payload = new ACE_Message_Block(bs/*ACE_DEFAULT_CDR_BUFFSIZE*/);
ACE_CDR::mb_align(payload);
ssize_t rec = strm.recv_n(payload->wr_ptr(), bs);
{
int i = ACE_OS::last_error();
payload->wr_ptr(bs);
char* p = payload->rd_ptr();
payload->release();
}
}