1 #include <msp/core/refptr.h>
2 #include <msp/net/resolve.h>
3 #include <msp/time/units.h>
16 user_agent("libmsphttp/0.1"),
28 void Client::use_event_dispatcher(IO::EventDispatcher *ed)
30 if(event_disp && sock)
31 event_disp->remove(*sock);
33 if(event_disp && sock)
34 event_disp->add(*sock);
37 void Client::start_request(const Request &r)
42 string host = r.get_header("Host");
43 if(host.find(':')==string::npos)
45 RefPtr<Net::SockAddr> addr = Net::resolve(host);
48 sock = new Net::StreamSocket(addr->get_family());
49 sock->set_block(false);
51 sock->signal_data_available.connect(sigc::mem_fun(this, &Client::data_available));
52 sock->signal_connect_finished.connect(sigc::mem_fun(this, &Client::connect_finished));
54 event_disp->add(*sock);
58 request = new Request(r);
59 if(!user_agent.empty())
60 request->set_header("User-Agent", user_agent);
67 const Response *Client::get_url(const std::string &url)
69 start_request(Request::from_url(url));
79 while(IO::PollEvent ev = IO::poll(*sock, sock->get_events(), Time::zero))
82 if(response && response->is_complete())
84 signal_response_complete.emit(*response);
93 void Client::wait_response()
95 while(request && (!response || !response->is_complete()))
107 void Client::connect_finished(const exception *err)
111 signal_socket_error.emit(*err);
117 sock->write(request->str());
120 void Client::data_available()
126 len = sock->read(rbuf, sizeof(rbuf));
128 catch(const exception &e)
130 signal_socket_error.emit(e);
136 in_buf.append(rbuf, len);
140 if(in_buf.find("\r\n\r\n")!=string::npos || in_buf.find("\n\n")!=string::npos)
142 response = new Response(Response::parse(in_buf));
143 response->set_user_data(request->get_user_data());
149 len = response->parse_content(in_buf);
150 in_buf.erase(0, len);
153 if(response && response->is_complete())
155 signal_response_complete.emit(*response);