bool XPathValidator::checkAgainstDTD(QString const &query) const { // If we cannot parse the query and traverse its AST without an exception, something // must be wrong with the query... try { QStringList subQueries = query.split("+|+"); // Create an emptry document and associate namespace resolvers with it. AutoDelete<xercesc::DOMDocument> document( xercesc::DOMImplementation::getImplementation()->createDocument()); AutoDelete<xercesc::DOMXPathNSResolver> resolver( document->createNSResolver(document->getDocumentElement())); resolver->addNamespaceBinding(X("fn"), X("http://www.w3.org/2005/xpath-functions")); resolver->addNamespaceBinding(X("xs"), X("http://www.w3.org/2001/XMLSchema")); foreach(QString subQuery, subQueries) { DynamicContext *ctx(s_xqilla.createContext(XQilla::XPATH2)); ctx->setXPath1CompatibilityMode(true); ctx->setNSResolver(resolver); AutoDelete<XQQuery> xqQuery(s_xqilla.parse(X(subQuery.toUtf8().constData()), ctx)); ASTNode *root = xqQuery->getQueryBody(); // std::cout << xqQuery->getQueryPlan() << std::endl; QSharedPointer<QueryScope> rootScope(new QueryScope()); rootScope->setNodeName("[document root]"); if (!inspect(root, rootScope, *d_dtd)) return false; } return true; } catch (XQException &e) {
int main(int argc, char* argv[]) { try { if (argc != 3) { std::cerr << "Usage: irc_client <host> <port>\n"; return 1; } boost::asio::io_service io_service; tcp::resolver resolver(io_service); tcp::resolver::query query(argv[1], argv[2]); tcp::resolver::iterator iterator = resolver.resolve(query); IRCClient c(io_service, iterator); io_service.run(); c.close(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
bool SharedLibrary::Relocate(LibraryList* lib_list, Vector<LibraryView*>* dependencies, Error* error) { // Apply relocations. LOG("%s: Applying relocations to %s\n", __FUNCTION__, base_name_); ElfRelocations relocations; if (!relocations.Init(&view_, error)) return false; #if defined(__arm__) || defined(__aarch64__) relocations.RegisterPackedRelocations(packed_relocations_); #endif SharedLibraryResolver resolver(this, lib_list, dependencies); if (!relocations.ApplyAll(&symbols_, &resolver, error)) return false; LOG("%s: Relocations applied for %s\n", __FUNCTION__, base_name_); return true; }
int main() { asio::io_service io_service; // resolve hostname asio::ip::tcp::resolver resolver(io_service); resolver.async_resolve({ "api.ipify.org", "80" }, [&](const auto& error, auto iterator) { if (error) { std::cout << error.message() << std::endl; return; } // connect to host auto socket = std::make_shared<asio::ip::tcp::socket>(io_service); asio::async_connect(*socket, iterator, [socket](const auto& error, auto) { if (error) { std::cout << error.message() << std::endl; return; } // send request asio::async_write(*socket, asio::buffer( "GET /?format=json HTTP/1.1\r\n" "Host: api.ipify.org\r\n" "Connection: close\r\n\r\n"), [socket](const auto& error, auto) { if (error) { std::cout << error.message() << std::endl; return; } // receive response, read until connection closed auto buffer = std::make_shared<std::array<char, 1024>>(); asio::async_read(*socket, asio::buffer(buffer->data(), buffer->size()), [socket, buffer](const auto&, auto size) { std::cout << std::string(buffer->data(), size) << std::endl; }); }); }); }); io_service.run(); return 0; }
bool SocketOutput::connect_to_server (const std::string &name) { std::map<std::string, std::string> rest_args; std::string baseurl; rest_args["port"] = socket_pvt::default_port; rest_args["host"] = socket_pvt::default_host; if (! Strutil::get_rest_arguments (name, baseurl, rest_args)) { error ("Invalid 'open ()' argument: %s", name.c_str ()); return false; } try { ip::tcp::resolver resolver (io); ip::tcp::resolver::query query (rest_args["host"].c_str (), rest_args["port"].c_str ()); ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve (query); ip::tcp::resolver::iterator end; boost::system::error_code err = error::host_not_found; while (err && endpoint_iterator != end) { socket.close (); socket.connect (*endpoint_iterator++, err); } if (err) { error ("Host \"%s\" not found", rest_args["host"].c_str ()); return false; } } catch (boost::system::system_error &err) { error ("Error while connecting: %s", err.what ()); return false; } catch (...) { error ("Error while connecting: unknown exception"); return false; } return true; }
void server_base::init(init_connectionhandler_func init_connection_handler, accept_handler_func accept_handler) { init_connection_handler(); if (!new_connection_) { throw std::invalid_argument("cannot initialize a server without a valid connection"); } // Open the acceptor with the option to reuse the address (i.e. SO_REUSEADDR). boost::asio::ip::tcp::resolver resolver(io_service_); boost::asio::ip::tcp::resolver::query query(settings_.listening_address, settings_.listening_port); boost::asio::ip::tcp::endpoint endpoint = *resolver.resolve(query); acceptor_.open(endpoint.protocol()); acceptor_.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); // bind to our port acceptor_.bind(endpoint); // listen for incoming requests acceptor_.listen(); // start the accept thread acceptor_.async_accept(new_connection_->socket(), accept_handler); }
void client_socket_utils::session_connect(socket_session_ptr pSession) { std::string& addr = pSession->get_remote_addr(); try { //注册关闭回调函数 pSession->installCloseCallBack(boost::bind(&client_socket_utils::close_callback, this, _1)); //注册读到数据回调函数 pSession->installReadDataCallBack(boost::bind(&client_socket_utils::read_data_callback, this, _1, _2, _3)); std::vector<std::string> ip_port; boost::split(ip_port, addr, boost::is_any_of(":")); if (ip_port.size() < 2) { //throw std::runtime_error("ip 格式不正确!"); LOG4CXX_ERROR(firebird_log, "[" << addr << "] ip 格式不正确!"); return; } tcp::resolver resolver(pSession->socket().get_io_service()); tcp::resolver::query query(ip_port[0], ip_port[1]); tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); //pSession->set_begin_endpoint(endpoint_iterator);//设置起始地址,以便重连 //由于客户端是不断重连的,即使还未连接也要保存该session m_manager.add_session(pSession); tcp::endpoint endpoint = *endpoint_iterator; pSession->socket().async_connect(endpoint, boost::bind(&client_socket_utils::handle_connect, this, boost::asio::placeholders::error, ++endpoint_iterator, pSession)); } catch (std::exception& e) { LOG4CXX_ERROR(firebird_log, KDS_CODE_INFO << "连接远程地址:[" << addr << "],socket异常:[" << e.what() << "]"); } catch (...) { LOG4CXX_ERROR(firebird_log, KDS_CODE_INFO << "连接远程地址:[" << addr << "],socket异常:[未知异常]"); } }
bool ping(const char* hostname) { // Prepare and resolve the host name boost::asio::ip::icmp::resolver::query query(boost::asio::ip::icmp::v4(), hostname, ""); boost::asio::ip::icmp::resolver resolver(io_service); boost::system::error_code ec; boost::asio::ip::icmp::endpoint destination = resolver.resolve(query, ec)->endpoint(); if (ec) return false; // Prepare the ICMP packet const int length = 256; char data[length]; memset(data, 0xff, length); // Send the ICMP packet boost::asio::ip::icmp::socket socket(io_service, boost::asio::ip::icmp::v4()); socket.send_to(boost::asio::buffer(data, length), destination); // Wait for a reply return true; }
void init(const boost::property_tree::ptree& pt) throw(std::runtime_error) { if (m_acceptor.is_open()) m_acceptor.close(); std::string url = pt.get<std::string>("address", "tcp://0.0.0.0:0"); std::string proto, addr, port, path; if (!parse_url(url, proto, addr, port, path)) THROW_RUNTIME_ERROR("Invalid URL address: " << url); if (proto != "tcp") THROW_RUNTIME_ERROR("Expected 'tcp' protocol type!"); if (port.empty() || port == "0") THROW_RUNTIME_ERROR("tcp_server invalid 'port' configuration: " << port); // Open the acceptor with the option to reuse the address (i.e. SO_REUSEADDR). boost::asio::ip::tcp::resolver resolver(this->m_io_service); boost::asio::ip::tcp::resolver::query query(addr, port); boost::asio::ip::tcp::endpoint end; m_endpoint = *resolver.resolve(query); if (m_endpoint == end) THROW_RUNTIME_ERROR("Error resolving address"); }
ClientConnection::ClientConnection( boost::asio::io_service& io_service, std::string address, int port ) : io_service( io_service ) { LOGTRACE(LT("Creating ClientConnection to "), address, LT(":"), port); // connect the socket to the requested endpoint boost::asio::ip::tcp::resolver resolver( io_service ); boost::asio::ip::tcp::resolver::query query( address, std::to_string( port ) ); boost::system::error_code ec; boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve( query, ec ); if (ec) LOGERROR(LT("Failed to resolve endpoint "), address, LT(":"), port, LT(" - "), ec.message()); try { this->socket = std::unique_ptr< boost::asio::ip::tcp::socket >(new boost::asio::ip::tcp::socket(io_service)); boost::asio::ip::tcp::resolver::iterator connected_endpoint = boost::asio::connect(*this->socket, endpoint_iterator); LOGFINE(LT("Connected - "), connected_endpoint->service_name(), LT(" - "), connected_endpoint->host_name()); } catch (boost::system::system_error e) { LOGERROR(LT("Failed to connect to "), address, LT(":"), port, LT(" - "), e.code().message()); } }
ssl::stream<tcp::socket> *NetworkConnector::connect(const std::string &address, unsigned int default_port, ssl::context *ctx, boost::system::error_code &ec) { std::string str_ip = address; std::string str_port = str_ip.substr(str_ip.find(':', 0) + 1, std::string::npos); str_ip = str_ip.substr(0, str_ip.find(':', 0)); tcp::resolver resolver(m_io_service); tcp::resolver::query query(str_ip, str_port); tcp::resolver::iterator it = resolver.resolve(query); ssl::stream<tcp::socket> *socket = new ssl::stream<tcp::socket>(m_io_service, *ctx); socket->next_layer().connect(*it, ec); if(ec.value() != 0) { delete socket; return nullptr; } return socket; }
server::server(const std::string& address, const std::string& port, std::size_t thread_pool_size) : thread_pool_size_(thread_pool_size), acceptor_(io_service_), new_connection_(new connection(io_service_, request_handler_)), request_handler_() { // Open the acceptor with the option to reuse the address (i.e. SO_REUSEADDR). boost::asio::ip::tcp::resolver resolver(io_service_); boost::asio::ip::tcp::resolver::query query(address, port); boost::asio::ip::tcp::endpoint endpoint = *resolver.resolve(query); acceptor_.open(endpoint.protocol()); acceptor_.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); acceptor_.bind(endpoint); acceptor_.listen(); acceptor_.async_accept(new_connection_->socket(), boost::bind(&server::handle_accept, this, boost::asio::placeholders::error)); // plog::instance()->set_file("http_proxy.exe.log"); // plog::instance()->set_output_type(postman::OUT_FILE); }
void CommandServer::createTcpEndpoint() { std::stringstream streamForPort; streamForPort << m_options.port; Ip::tcp::resolver resolver(m_tcpAcceptor.get_io_service()); // TODO: support ipv6 Ip::tcp::resolver::query query(Ip::tcp::v4(), m_options.host, streamForPort.str(), Ip::resolver_query_base::numeric_service); Ip::tcp::endpoint endpoint = *resolver.resolve(query); m_tcpAcceptor.open(endpoint.protocol()); m_tcpAcceptor.set_option(Ip::tcp::acceptor::reuse_address(true)); m_tcpAcceptor.bind(endpoint); m_tcpAcceptor.listen(); LOG(info) << "Listening on " << endpoint; startAcceptOnTcp(); }
void InspectorHeapProfilerAgent::takeHeapSnapshot(ErrorString* errorString, const bool* reportProgress) { v8::HeapProfiler* profiler = m_isolate->GetHeapProfiler(); if (!profiler) { *errorString = "Cannot access v8 heap profiler"; return; } OwnPtr<HeapSnapshotProgress> progress; if (asBool(reportProgress)) progress = adoptPtr(new HeapSnapshotProgress(frontend())); v8::HandleScope handleScope(m_isolate); // Remove? GlobalObjectNameResolver resolver(m_isolate); const v8::HeapSnapshot* snapshot = profiler->TakeHeapSnapshot(progress.get(), &resolver); if (!snapshot) { *errorString = "Failed to take heap snapshot"; return; } HeapSnapshotOutputStream stream(frontend()); snapshot->Serialize(&stream); const_cast<v8::HeapSnapshot*>(snapshot)->Delete(); }
int Resolver::resolve(Compiler& compiler, Module& module, Resolver* parent, ResolvedProcedure* procedure, bool isModuleBody, gc<Pattern> leftParam, gc<Pattern> rightParam, gc<Pattern> valueParam, gc<Expr> body) { Resolver resolver(compiler, module, parent, isModuleBody); // Create a scope for the body. Scope scope(&resolver); resolver.scope_ = &scope; // First, we allocate slots for the destructured parameters. We do this // first so that all parameter slots for the method are contiguous at the // beginning of the method's slot window. The caller will assume this when // it sets up the arguments before the call. resolver.allocateSlotsForParam(leftParam); resolver.allocateSlotsForParam(rightParam); resolver.allocateSlotsForParam(valueParam); // Create a slot for the result value. resolver.makeLocal(new SourcePos(NULL, 0, 0, 0, 0), String::create("(result)")); // Now that we've got our slots set up, we can actually resolve the nested // patterns for the param (if there are any). resolver.destructureParam(leftParam); resolver.destructureParam(rightParam); resolver.destructureParam(valueParam); resolver.resolve(body); scope.end(); // TODO(bob): Copying this stuff here is lame. procedure->resolve(resolver.maxLocals_, resolver.closures_); return resolver.maxLocals_; }
int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: daytime_client <host>" << std::endl; return 1; } boost::asio::io_service io_service; // Set the name of the file that all logger instances will use. services::logger logger(io_service, ""); logger.use_file("log.txt"); // Resolve the address corresponding to the given host. boost::asio::ip::tcp::resolver resolver(io_service); boost::asio::ip::tcp::resolver::query query(argv[1], "daytime"); boost::asio::ip::tcp::resolver::iterator iterator = resolver.resolve(query); boost::asio::ip::tcp::endpoint endpoint = *iterator; // Start an asynchronous connect. debug_stream_socket socket(io_service); socket.async_connect(endpoint, boost::bind(connect_handler, boost::asio::placeholders::error, &socket, ++iterator)); // Run the io_service until all operations have finished. io_service.run(); } catch (std::exception& e) { std::cerr << e.what() << std::endl; } return 0; }
boost::asio::ip::tcp::resolver::iterator ApnsService::resolver_addr(bool feedback) { std::string addr; std::string port; if (!feedback) { addr.assign(HOST_PRODUCTION_ENV); port.assign(PORT_PRODUCTION_ENV); if (apns_params_.Developer) { addr.assign(HOST_DEVELOPMENT_ENV); port.assign(PORT_DEVELOPMENT_ENV); } } else { addr.assign(FEEDBACK_HOST_PRODUCTION_ENV); port.assign(FEEDBACK_PORT_PRODUCTION_ENV); if (apns_params_.Developer) { addr.assign(FEEDBACK_HOST_DEVELOPMENT_ENV); port.assign(FEEDBACK_PORT_DEVELOPMENT_ENV); } } boost::asio::ip::tcp::resolver resolver(*io_service_); boost::asio::ip::tcp::resolver::query query(addr, port); boost::asio::ip::tcp::resolver::iterator iterator = boost::asio::ip::tcp::resolver::iterator(); try { iterator = resolver.resolve(query); } catch (const boost::system::system_error& err) { LOGFMTE("resolver error:%s", err.what()); } return iterator; }
//using namespace udp; asio::ip::udp::endpoint resolve(const asio::ip::udp::resolver::query &q) { asio::ip::udp::endpoint ep; fibers::detail::fiber_ptr_t this_fiber(fibers::detail::fiber_object::current_fiber_->shared_from_this()); asio::ip::udp::resolver resolver(this_fiber->io_service_); CHECK_CALLER(this_fiber); if (this_fiber->caller_) { (*(this_fiber->caller_))([this_fiber, &q, &ep, &resolver](){ this_fiber->state_=fibers::detail::fiber_object::BLOCKED; resolver.async_resolve(q, (this_fiber->fiber_strand_.wrap([this_fiber, &ep](const std::error_code &ec, asio::ip::udp::resolver::iterator iterator){ this_fiber->last_error_=ec; if (!ec) { ep=*iterator; } this_fiber->state_=fibers::detail::fiber_object::RUNNING; this_fiber->one_step(); }))); }); } else { // TODO: Error } this_fiber->throw_on_error(); return ep; }
void start(const std::string & ip_addr, const std::string & port) { ip::tcp::resolver resolver(io_service_pool_.get_now_io_service()); ip::tcp::resolver::query query(ip_addr, port); ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); boost::asio::ip::tcp::endpoint endpoint = *resolver.resolve(query); boost::system::error_code ec; acceptor_.open(endpoint.protocol(), ec); if (ec) { // Open endpoint error std::cout << "async_asio_echo_serv_ex::start() - Error: (code = " << ec.value() << ") " << ec.message().c_str() << std::endl; return; } boost::asio::socket_base::reuse_address option(true); acceptor_.set_option(option); acceptor_.bind(endpoint); acceptor_.listen(); do_accept(); }
// analayze semantic information... // In current implement, analayze phase is separated to 2 steps. // One is building phase which create scoep tree. // And the other one is resolving phase. // DCC syntax not need multi step analayzer, // but I implement it because for future improvement, // and for studying how to implement multi phase analyzer. dcc::semantic::scope::symbol_table semantic_analayzer::analyze(dcc::ast::module &mod){ // create symbol table auto root = std::make_shared<dcc::semantic::scope::global_scope>(); scope_builder builder(root); dcc::ast::helper::traverse(builder, mod); if(builder.error_counts() > 0){ builder.dump_errors(); // throw exception throw semantic_exception(); } // resolve symbol symbol_resolver resolver(root); dcc::ast::helper::traverse(resolver, mod); if(resolver.error_counts() > 0){ resolver.dump_errors(); // throw exception throw semantic_exception(); } return dcc::semantic::scope::symbol_table(root); }
void TcpRpcChannel::startConnect() { //if already stopped if (stop_) { return; } boost::system::error_code ec; //close the socket at first sock_.close(ec); //start to resolve the address tcp::resolver resolver(io_service_initializer_->get_io_service()); tcp::resolver::query query(serverAddr_, serverPort_); tcp::resolver::iterator iter = resolver.resolve(query, ec); if (ec) { GOOGLE_LOG(ERROR) << "fail a resolve server address " << serverAddr_ << ":" << serverPort_; } else { receivedMsg_.clear(); doConnect(iter); } }
Client::Client( boost::asio::io_service& io_service, boost::asio::ssl::context& context ): socket_(io_service, context) { try{ boost::asio::ip::tcp::resolver resolver(io_service); boost::asio::ip::tcp::resolver::query query("smtp.gmail.com", "465"); boost::asio::connect(socket_.lowest_layer(), resolver.resolve(query)); socket_.lowest_layer().set_option(boost::asio::ip::tcp::no_delay(true)); socket_.set_verify_callback(boost::asio::ssl::rfc2818_verification("smtp.gmail.com")); socket_.handshake(boost::asio::ssl::stream<boost::asio::ip::tcp::socket>::client); std::cout << "pripojeno" << std::endl; connected = 1; get_response(); std::string msg = "ehlo smtp.gmail.com\r\n"; send_message(msg); get_response(); } catch(std::exception& e){ std::cout << "vyjimka: " << e.what() << std::endl; connected = 0; } }
USBTester::USBTester(USBPhy *phy, uint16_t vendor_id, uint16_t product_id, uint16_t product_release): USBDevice(phy, vendor_id, product_id, product_release), interface_0_alt_set(NONE), interface_1_alt_set(NONE), configuration_set(NONE), reset_count(0), suspend_count(0), resume_count(0) { EndpointResolver resolver(endpoint_table()); resolver.endpoint_ctrl(64); bulk_in = resolver.endpoint_in(USB_EP_TYPE_BULK, 64); bulk_out = resolver.endpoint_out(USB_EP_TYPE_BULK, 64); int_in = resolver.endpoint_in(USB_EP_TYPE_INT, 64); int_out = resolver.endpoint_out(USB_EP_TYPE_INT, 64); MBED_ASSERT(resolver.valid()); queue = mbed::mbed_highprio_event_queue(); configuration_desc(0); init(); USBDevice::connect(); flags.wait_any(EVENT_READY, osWaitForever, false); }
void client::connect(const std::string& hostname, int port) { if (_running) { return; } if (!_encryption->last_error().empty()) { error(-1, _encryption->last_error()); return; } _running = true; tcp::resolver resolver(_service); tcp::resolver::query resolver_query(hostname, std::to_string(port)); _endpoint = resolver.resolve(resolver_query); try_connect(); }
NetworkDevice(Stats &stats, const char *address) : Device(stats), socket(io_service) { stringstream portstr; portstr << SERVER_PORT; tcp::resolver resolver(io_service); tcp::resolver::query query(address, portstr.str()); tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); tcp::resolver::iterator end; boost::system::error_code error = boost::asio::error::host_not_found; while(error && endpoint_iterator != end) { socket.close(); socket.connect(*endpoint_iterator++, error); } if(error) throw boost::system::system_error(error); mem_counter = 0; }
int VirtualAMHSDevice::Connect(string strIP, int nPort) { if (NULL != m_pClient) { return -1; } m_sIP = strIP; m_nPort = nPort; char buf[10] = ""; _itoa_s(nPort, buf, 10); tcp::resolver resolver(m_io_service); tcp::resolver::query query(strIP, buf); tcp::resolver::iterator iterator = resolver.resolve(query); m_pClient = new amhs_client(m_io_service, iterator); m_pClient->m_pHandleCommand = (ProcessCommand)&VirtualAMHSDevice::PassCommand; m_pClient->m_pVirtualDevice = this; m_thread = boost::thread(boost::bind(&boost::asio::io_service::run, &m_io_service)); return 0; }
/** * Check if a visibility/accessibility change would turn a method referenced * in a callee to virtual methods as they are inlined into the caller. * That is, once a callee is inlined we need to ensure that everything that was * referenced by a callee is visible and accessible in the caller context. * This step would not be needed if we changed all private instance to static. */ bool MultiMethodInliner::create_vmethod(DexInstruction* insn) { auto opcode = insn->opcode(); if (opcode == OPCODE_INVOKE_DIRECT || opcode == OPCODE_INVOKE_DIRECT_RANGE) { auto method = static_cast<DexOpcodeMethod*>(insn)->get_method(); method = resolver(method, MethodSearch::Direct); if (method == nullptr) { info.need_vmethod++; return true; } always_assert(method->is_def()); if (is_init(method)) { if (!method->is_concrete() && !is_public(method)) { info.non_pub_ctor++; return true; } // concrete ctors we can handle because they stay invoke_direct return false; } info.need_vmethod++; return true; } return false; }
int main(int argc, const char** argv ) { if (argc != 3) { std::cout << "Usage: client <server ip> <port>\n"; std::cout << "Example:\n"; std::cout << " client 127.0.0.1 8080\n"; return -1; } boost::asio::io_service io_service; boost::asio::ip::tcp::socket socket(io_service); boost::asio::ip::tcp::resolver resolver(io_service); boost::asio::ip::tcp::resolver::query query(argv[1], argv[2]); boost::asio::ip::tcp::resolver::iterator server_endpoint = resolver.resolve(query); boost::asio::connect( socket, server_endpoint ); std::cout << "Enter message: "; char request[max_length]; std::cin.getline(request, max_length); size_t request_length = std::strlen(request); boost::asio::write( socket, boost::asio::buffer( request, request_length ) ); //char reply[max_length]; //size_t reply_length = boost::asio::read( socket, boost::asio::buffer( reply, request_length ) ); //std::cout << "Reply is: "; //std::cout.write(reply, reply_length); //std::cout << "\n"; return 0; }
server::server(const std::string& address, const std::string& port, std::size_t io_service_pool_size, const database::mysql_config& config) : io_service_pool_(io_service_pool_size), signals_(io_service_pool_.get_io_service()), acceptor_(io_service_pool_.get_io_service()), new_connection_(), database_handler_(config, io_service_pool_size), next_request_handler_(0) { for (std::size_t i = 0; i < io_service_pool_size; ++i) { request_handler_ptr handler(new restful_request_handler( database_handler_.get_connection())); request_handlers_.push_back(handler); } // Register to handle the signals that indicate when the server should exit. // It is safe to register for the same signal multiple times in a program, // provided all registration for the specified signal is made through Asio. signals_.add(SIGINT); signals_.add(SIGTERM); #if defined(SIGQUIT) signals_.add(SIGQUIT); #endif // defined(SIGQUIT) signals_.async_wait(boost::bind(&server::handle_stop, this)); // Open the acceptor with the option to reuse the address (i.e. SO_REUSEADDR) boost::asio::ip::tcp::resolver resolver(acceptor_.get_io_service()); boost::asio::ip::tcp::resolver::query query(address, port); boost::asio::ip::tcp::endpoint endpoint = *resolver.resolve(query); acceptor_.open(endpoint.protocol()); acceptor_.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); acceptor_.bind(endpoint); acceptor_.listen(); start_accept(); }
bool Simloid::init () throw () { #ifdef FOUND_boost _initialized = true; _io = new boost::asio::io_service(); _socket = new tcp::socket(*_io); tcp::resolver resolver(*_io); tcp::resolver::query query("localhost", "7777"); tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); tcp::resolver::iterator end; boost::system::error_code error = boost::asio::error::host_not_found; while (error && endpoint_iterator != end) { _socket->close(); _socket->connect(*endpoint_iterator++, error); } if (error) return false; for (int i=0; i<19; i++) _target[i] = _hold ? 512 : -1; std::ostream request_stream(&_request); for (int i=1; i<20; i++) request_stream << "(pid " << i << " 512)\n"; request_stream << "(done)\n"; boost::asio::write(*_socket, _request); step(); return true; #else _initialized = false; std::cout << "Error: cannot initialize Simloid interface without boost libraries." << std::endl; return false; #endif }