• HOME
  • DOCS
  • WTF
  • TECH
  • LIFE
  • PAGES
    • ARCHIVE
    • TAGS
    • ABOUT
    • FRIENDS
    • RSS
  • TOOLS
    • GEO
    • RANDOM()
    • GOO.GL
    • CSS HEART
Aj's Blog

记录时间溜走的瞬间和折腾过的那些事

wxWidgets几种网络通讯方式的实现和对比: wxHTTP / wxURL / wxSocket
2012-09-20 @ TECH wxHTTPwxSocketwxURLwxWidgets

一、wxHTTP方式

头文件
#include <wx/protocol/http.h>
#include <wx/sstream.h>

示例

	wxString domain = "www.google.com";
	wxString url = "/ncr";
	wxString res = "";

	wxHTTP h;
	if( h.Connect( domain ) )
	{
		wxInputStream *in = h.GetInputStream( url );
		wxStringOutputStream out(&res);
		if( in && in->IsOk() )
		{
			in->Read( out );
		}
		delete in;
	}
	h.Close();

优缺点
可以自定义HttpHeader,但是Http响应要等待响应结束,会造成程序假死

二、wxURL方式

头文件
#include <wx/url.h>
#include <wx/sstream.h>

示例

	wxString domain = "www.google.com";
	wxString url = "/ncr";
	wxString res = "";

	wxURL h( "http://" + domain + url );
	if( h.GetError() == wxURL_NOERR )
	{
		wxInputStream *in	= h.GetInputStream();
		wxStringOutputStream out(&res);
		if( in && in->IsOk() )
		{
			in->Read( out );
		}
		delete in;
	}

优缺点
不可自定义Httpheader,效率相对wxHTTP好一些

三、wxSocket方式

头文件
#include <wx/socket.h>
#include <wx/sstream.h>
#include <wx/sckstrm.h>

示例

	//基本配置部分
	wxString sock_ret = "";
	const long ID_SOCKET = wxNewId();

	BEGIN_EVENT_TABLE(YOURAPP,wxDialog)
		EVT_SOCKET			(ID_SOCKET	, YOURAPP::SocketEvent)
	END_EVENT_TABLE()

	//发送请求
	void CPADialog::SocketGet(const wxString& domain,
                                  const wxString& url,
                                  const wxString& refer,
                                  const wxString& cookie)
	{
		wxSocketClient 	*client = new wxSocketClient();
		wxIPV4address	*host	= new wxIPV4address();
		host->Hostname(domain);
		host->Service( 80 );

		client->SetEventHandler( *this, ID_SOCKET);
		client->SetNotify( wxSOCKET_INPUT_FLAG );
		client->Notify( true );

		wxString _all	= "GET "+ url + " HTTP/1.1\r\n";
		_all += "Host: "+ domain +"\r\n";
		_all += "Connection: Close\r\n";
		if( !refer.IsEmpty() ) _all += "Referer: "+ refer +"\r\n";
		if( !cookie.IsEmpty() ) _all += "Cookie: */*\r\n";
		_all +=	"\r\n";
		client->SetTimeout(30);
		if( client->Connect( *host, true ) )
		{
			client->Write( _all.mb_str(), strlen(_all.mb_str()) );
		}
	}

	//EVT_SOCKET Handler
	void CPADialog::SocketEvent(wxSocketEvent& event)
	{
		wxSocketBase *client = event.GetSocket();
		wxSocketInputStream in(*client);
		wxStringOutputStream out(&sock_ret);
		wxCommandEvent *caller = NULL ;
		if( in.IsOk() )
		{
			in.Read( out );
			client->Close();
			//callback and do something
		}
	}

优缺点
完全自定义任何通讯内容,但是需要设置EVT_SOCKET事件获取相应

下一篇:   wxWidgets中 wxButton实现自动点击
上一篇:   wxWidgets如何解析ini配置文件
暂无评论

Cancel reply