实现一个整型函数 int request (char* hostname, char* api, char* parameters, string& message) 主要分为建立udp,发送信令,接收服务器返回信令,接收数据三个部分功能 首先建立UDP:
#ifdef WIN_OS
{ WSADATA WsaData; WSAStartup (0x0101, &WsaData); } #endif
sockaddr_in sin;
int sock = socket (AF_INET, SOCK_STREAM, 0); if (sock == -1)
{
return -100; } sin.sin_family = AF_INET; sin.sin_port = htons( (unsigned short)8080);
struct hostent * host_addr = gethostbyname(hostname);
if(host_addr==NULL)
{
cout<<"Unable to locate host"<<endl ; return -103; } sin.sin_addr.s_addr = *((int*)*host_addr->h_addr_list) ; cout<<"Port :"<<sin.sin_port<<", Address : "<< sin.sin_addr.s_addr<<endl;
if( connect (sock,(const struct sockaddr *)&sin, sizeof(sockaddr_in) ) == -1 )
{
cout<<"connect failed"<<endl ; return -101; }
其次定义一个宏:
#define SEND_RQ(MSG) send(sock,MSG,strlen(MSG),0);
向服务器发送信令:
SEND_RQ("GET ");
char* api;//这里填URL文件名,比如
http://127.0.0.1:8888/1.asf中的1.asf
SEND_RQ(api); SEND_RQ("HTTP/1.0\r\n"); SEND_RQ("Accept: */*\r\n"); SEND_RQ("User-Agent: NSPlayer/4.1.0.3925\r\n");
char content_header[100];
sprintf(content_header,"Content-Length: %d\r\n",strlen(parameters)); SEND_RQ(content_header); SEND_RQ("Host: "); SEND_RQ("hostname"); SEND_RQ("\r\n"); //If you need to send a basic authorization //string Auth = "username:password"; //Figureout a way to encode test into base64 ! //string AuthInfo = base64_encode(reinterpret_cast<const unsigned char*>(Auth.c_str()),Auth.length()); //string sPassReq = "Authorization: Basic " + AuthInfo; //SEND_RQ(sPassReq.c_str());
SEND_RQ("\r\n");
SEND_RQ("\r\n"); SEND_RQ(parameters); SEND_RQ("\r\n");
接受服务器发送反馈信令:
//接收头部
cout<<"####HEADER####"<<endl;
char c1[1]; int l,line_length; bool loop = true; bool bHeader = false;
while(loop)
{ l = recv(sock, c1, 1023, 0); if(l<0) loop = false; if(c1[0]=='\n')
{
if(line_length == 0) loop = false;
line_length = 0;
if(message.find("200") != string::npos) bHeader = true;
}
else if(c1[0]!='\r') line_length++; cout<<c1[0]; message += c1[0]; }
//接收body
message="";
if(bHeader) {
cout<<"####BODY####"<<endl ;
char p[1024]; while((l = recv(sock,p,1023,0)) > 0)
{
cout.write(p,l) ; p[l] = '\0'; message += p; } cout << message.c_str(); } else { return -102; } //清理工作 #ifdef WIN_OS WSACleanup( ); #endif //------------------------------------------------------------------------------------------------------------------------------------------------- 相关的协议信令: RTSP协议 //RTSP HTTP STREAM协议 //HTTP STREAM |
用UDP实现HTTP Streaming协议从指定的URL拉流
最新推荐文章于 2024-09-27 16:31:42 发布