コード例 #1
0
ファイル: StreamDump.cpp プロジェクト: hamling-ling/KirinCam
void connectSocket(boost::asio::io_service& io_service, tcp::socket& socket, const std::string& url, const std::string &port) {
	boost::system::error_code error = boost::asio::error::host_not_found;

	// connect
	if (isIpAddress(url.c_str())) {
		boost::asio::ip::address addr = boost::asio::ip::address::from_string(url);
		boost::asio::ip::tcp::endpoint endpoint = boost::asio::ip::tcp::endpoint(addr, lexical_cast<int>(port));
		socket.close();
		socket.connect(endpoint);
	}
	else {
		tcp::resolver::query query(url, "http");
		tcp::resolver resolver(io_service);
		tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
		tcp::resolver::iterator end;

		while (error && endpoint_iterator != end)
		{
			socket.close();
			socket.connect(*endpoint_iterator++, error);
		}
		if (error)
			throw boost::system::system_error(error);
	}
}
コード例 #2
0
	// Conexion al servidor
	void handle_connect(const boost::system::error_code& error, tcp::resolver::iterator endpoint_iterator){
		debugOUT("handle_connect");
		if (!error){
			connected = true;
			debugOUT("Connected");

			boost::asio::async_read(socket_,
									boost::asio::buffer(receiveBuffer, transferAtLeast),
									boost::asio::transfer_at_least(transferAtLeast),
									boost::bind(&TCPClient::handle_read, this,
									boost::asio::placeholders::error,
									boost::asio::placeholders::bytes_transferred));

			debugOUT("async_read dispatched");
		}
		else if (endpoint_iterator != tcp::resolver::iterator()){
			debugOUT("Next Endpoint");
			// Conexion fallida, intentemos con el siguiente endpoint
			socket_.close();
			tcp::endpoint endpoint = *endpoint_iterator;
			
			socket_.async_connect(	endpoint,
									boost::bind(&TCPClient::handle_connect, this,
									boost::asio::placeholders::error, ++endpoint_iterator));
		}
		else{
			debugOUT("Error: " << error.message());
		}
	}
コード例 #3
0
awaitable<void> echo(tcp::socket s)
{
 auto token = co_await this_coro::token();

 try
 {
   char data1[1024];
   char data2[1024];

   char* p1 = data1;
   char* p2 = data2;

   // Perform initial read into first buffer.
   size_t n = co_await s.async_read_some(boost::asio::buffer(p1, 1024), token);

   for (;;)
   {
     // Swap received data to other buffer and initiate write operation.
     std::swap(p1, p2);
     auto write_result = boost::asio::async_write(s, boost::asio::buffer(p2, n), token);

     // Perform next read while write operation is in progress.
     n = co_await s.async_read_some(boost::asio::buffer(p1, 1024), token);

     // Wait for write operation to complete before proceeding.
     co_await write_result;
   }
 }
 catch (std::exception& e)
 {
   std::printf("echo Exception: %s\n", e.what());
 }
}
コード例 #4
0
ファイル: transmit_file.cpp プロジェクト: barrbrain/asio
void transmit_file(tcp::socket& socket,
    random_access_handle& file, Handler handler)
{
  // Construct an OVERLAPPED-derived object to contain the handler.
  overlapped_ptr overlapped(socket.get_io_service(), handler);

  // Initiate the TransmitFile operation.
  BOOL ok = ::TransmitFile(socket.native(),
      file.native(), 0, 0, overlapped.get(), 0, 0);
  DWORD last_error = ::GetLastError();

  // Check if the operation completed immediately.
  if (!ok && last_error != ERROR_IO_PENDING)
  {
    // The operation completed immediately, so a completion notification needs
    // to be posted. When complete() is called, ownership of the OVERLAPPED-
    // derived object passes to the io_service.
    asio::error_code ec(last_error,
        asio::error::get_system_category());
    overlapped.complete(ec, 0);
  }
  else
  {
    // The operation was successfully initiated, so ownership of the
    // OVERLAPPED-derived object has passed to the io_service.
    overlapped.release();
  }
}
コード例 #5
0
ファイル: TCPServer.cpp プロジェクト: gitmesen/carla
 static void CloseConnection(tcp::acceptor &_acceptor, tcp::socket &_socket) {
   log_info(LOG_PREFIX, "disconnecting");
   if (_acceptor.is_open()) {
     _acceptor.close();
   }
   if (_socket.is_open()) {
     _socket.close();
   }
 }
コード例 #6
0
		void EthernetRelayDriver::configure(std::string host, int port){

			tcp::endpoint endpoint(boost::asio::ip::address::from_string(host.c_str()), port);
			socket.connect(endpoint);

			if(socket.is_open()){
				ROS_INFO("TCP/IP socket opened.");
			}
		}
コード例 #7
0
ファイル: Client.cpp プロジェクト: gogo-dev/GoGo
static void really_disconnect(tcp::socket& socket, Logger* logger)
{
	try {
		socket.shutdown(socket_base::shutdown_both);
		socket.close();
	} catch(const system::system_error& e) {
		// This might be totally okay. Depends on the error.
		logger->warning(format("Failed to shut down the socket. This shouldn't happen! (%1%)") % e.what());
	}
}
コード例 #8
0
ファイル: tcp_server.cpp プロジェクト: scp1513/cppserver
inline void TCPServerSession::Start()
{
	mBuffer.resize(sizeof(uint16));

	mSocket.set_option(tcp::no_delay(mCore.tcp_nodelay));
	mSocket.set_option(tcp::socket::keep_alive(false));
	mSocket.set_option(tcp::socket::send_buffer_size(mCore.send_buffer_size));
	mSocket.set_option(tcp::socket::receive_buffer_size(mCore.recv_buffer_size));

	recv_len();
}
コード例 #9
0
ファイル: asio_sender.cpp プロジェクト: asimonov-im/wesnoth
void asio_sender::send(ana::detail::shared_buffer buffer ,
                       tcp::socket&               socket ,
                       ana::send_handler*         handler,
                       ana::detail::sender*       sender ,
                       ana::operation_id          op_id  )
{
    ana::timer* running_timer( NULL );
    try
    {
        if ( sender->timeouts_enabled() )
        {
            running_timer = sender->create_timer();

            sender->start_timer( running_timer, buffer,
                                boost::bind(&asio_sender::handle_send, this,
                                            boost::asio::placeholders::error, handler,
                                            running_timer, op_id, true ) );
        }

        stats_collector().start_send_packet(  buffer->size()
                                            + ( raw_mode() ? 0 : ana::HEADER_LENGTH ) );

        if ( raw_mode() )
        {
            socket.async_write_some( boost::asio::buffer(buffer->base(), buffer->size() ),
                                     boost::bind(&asio_sender::handle_partial_send,this,
                                                 buffer, boost::asio::placeholders::error,
                                                 &socket, handler, running_timer, 0, _2, op_id ));
        }
        else
        {
            ana::ana_uint32 size( buffer->size() );
            ana::host_to_network_long( size );

            ana::serializer::bostream* output_stream = new ana::serializer::bostream();
            (*output_stream) << size;

            //write the header first in a separate operation, then send the full buffer
            socket.async_write_some( boost::asio::buffer( output_stream->str() ),
                                     boost::bind(&asio_sender::handle_sent_header,this,
                                                 boost::asio::placeholders::error, output_stream,
                                                 &socket, buffer,
                                                 handler, running_timer, _2, op_id ));
        }
    }
    catch(const std::exception&)
    {
        disconnect();
        delete running_timer;
    }
}
コード例 #10
0
ファイル: tcp_server.cpp プロジェクト: scp1513/cppserver
inline bool TCPServerSession::Close()
{
	try
	{
		if (!mSocket.is_open()) return false;
		mSocket.shutdown(socket_base::shutdown_both);
		mSocket.close();
		return true;
	}
	catch (...)
	{
		return false;
	}
}
コード例 #11
0
ファイル: composed_3.cpp プロジェクト: boostorg/asio
  void operator()(CompletionHandler&& completion_handler,
      tcp::socket& socket, const char* message) const
  {
    // The async_write operation has a completion handler signature of:
    //
    //   void(boost::system::error_code error, std::size n)
    //
    // This differs from our operation's signature in that it is also passed
    // the number of bytes transferred as an argument of type std::size_t. We
    // will adapt our completion handler to async_write's completion handler
    // signature by using std::bind, which drops the additional argument.
    //
    // However, it is essential to the correctness of our composed operation
    // that we preserve the executor of the user-supplied completion handler.
    // The std::bind function will not do this for us, so we must do this by
    // first obtaining the completion handler's associated executor (defaulting
    // to the I/O executor - in this case the executor of the socket - if the
    // completion handler does not have its own) ...
    auto executor = boost::asio::get_associated_executor(
        completion_handler, socket.get_executor());

    // ... and then binding this executor to our adapted completion handler
    // using the boost::asio::bind_executor function.
    boost::asio::async_write(socket,
        boost::asio::buffer(message, std::strlen(message)),
        boost::asio::bind_executor(executor,
          std::bind(std::forward<CompletionHandler>(
            completion_handler), std::placeholders::_1)));
  }
コード例 #12
0
bool recvFile(tcp::socket &socket, std::string filepath) {
    std::fstream file;
    file.open(filepath, std::ios::out | std::ios::binary);
    if(!file.is_open()) return false;
    size_t file_size = 0;
    boost::asio::read(socket, boost::asio::buffer(&file_size, sizeof(file_size)));
    size_t file_count = 0;
    while(file_count < file_size) {
        
        char buffer[1024];
        memset(buffer, 0, sizeof(buffer));
        boost::system::error_code ecode;
        size_t buffer_size = socket.read_some(boost::asio::buffer(buffer, 1024), ecode);
        if(ecode == boost::asio::error::eof)
            break;
        else if(ecode) throw boost::system::system_error(ecode);
        
        file.write(buffer,buffer_size);
        file_count += buffer_size;
        std::cout << ".";
        
        /*
        boost::array<char, 128> ar;
        boost::system::error_code ecode;
        size_t len = socket.read_some(boost::asio::buffer(ar), ecode);
        if(ecode == boost::asio::error::eof) break;
        else if(ecode) throw boost::system::system_error(ecode);
        file.write(ar.data(), len);
        */
    }
    file.close();
    return true;
}
コード例 #13
0
		void send_client()
		{
			std::shared_ptr<string> message =
					std::make_shared<string>("CLIENT " + to_string(id) + "\n");
			tcp_socket->async_send(ba::buffer(*message),
						boost::bind(packet_sent, _1, _2, this, message));
		}
コード例 #14
0
ファイル: main.cpp プロジェクト: DeadHunter/TuxNet
TextRconPacket getResponse(tcp::socket & socket)
{
	boost::array<char, 16384> buf;
	uint8_t responseHeaderBuf[BinaryRconPacketHeader::Size];
	
	size_t len = socket.read_some(boost::asio::buffer(buf));

	for(uint8_t pos = 0; pos < BinaryRconPacketHeader::Size; pos++)
		responseHeaderBuf[pos] = buf[pos];

	BinaryRconPacketHeader binaryRconPacketHeader(responseHeaderBuf);

	if(!binaryRconPacketHeader.isValid())
		throw string("Invalid Binary Packet Header");
	
	uint32_t binaryRconResponsePacketSize = binaryRconPacketHeader.getPacketSize();
	uint32_t binaryRconResponseBodySize = binaryRconResponsePacketSize - BinaryRconPacketHeader::Size;

	uint8_t* responseBodyBuf = new uint8_t[binaryRconResponseBodySize];

	for(uint32_t pos = 0; pos < binaryRconResponseBodySize; pos++)
		responseBodyBuf[pos] = buf[pos + BinaryRconPacketHeader::Size];

	BinaryRconPacket binaryResponse(binaryRconPacketHeader, responseBodyBuf);

	if(!binaryResponse.isValid())
		throw string("Invalid Binary Packet");

	return TextRconPacket(binaryResponse);
}
コード例 #15
0
    void send_bad_response(
        http::status status,
        std::string const& error)
    {
        string_response_.emplace(
            std::piecewise_construct,
            std::make_tuple(),
            std::make_tuple(alloc_));

        string_response_->result(status);
        string_response_->keep_alive(false);
        string_response_->set(http::field::server, "Beast");
        string_response_->set(http::field::content_type, "text/plain");
        string_response_->body() = error;
        string_response_->prepare_payload();

        string_serializer_.emplace(*string_response_);

        http::async_write(
            socket_,
            *string_serializer_,
            [this](boost::beast::error_code ec, std::size_t)
            {
                socket_.shutdown(tcp::socket::shutdown_send, ec);
                string_serializer_.reset();
                string_response_.reset();
                accept();
            });
    }
コード例 #16
0
    void accept()
    {
        // Clean up any previous connection.
        boost::beast::error_code ec;
        socket_.close(ec);
        buffer_.consume(buffer_.size());

        acceptor_.async_accept(
            socket_,
            [this](boost::beast::error_code ec)
            {
                if (ec)
                {
                    accept();
                }
                else
                {
                    // Request must be fully processed within 60 seconds.
                    request_deadline_.expires_after(
                        std::chrono::seconds(60));

                    read_request();
                }
            });
    }
コード例 #17
0
ファイル: main.cpp プロジェクト: nikitaband1t/finalProject
 void handle_read(const boost::system::error_code &error,
                  size_t bytes_transferred) {
     if (!error) {
         std::string query(data_);
         std::string *file = new std::string("");
         file->append(directory.c_str()).append(strtok((strtok((char *) (query.c_str()), "GET ")),"?="));
         FILE*f = fopen("/home/box/output.txt","w");
         fwrite(file->c_str(),1,file->size(),f);
         fclose(f);
         FILE *file_ptr = fopen(file->c_str(), "r");
         if (file_ptr != nullptr) {
             boost::asio::write(socket_, boost::asio::buffer(found,strlen(found)));
             for (int bytes_read = fread(data_, sizeof(char), 1024, file_ptr); bytes_read != 0;
                 bytes_read = fread(data_, sizeof(char), 1024, file_ptr)) {
                 std::string deliver(data_);
                 boost::asio::write(socket_, boost::asio::buffer(deliver.c_str(),bytes_read));
             }
         } else {
             boost::asio::write(socket_, boost::asio::buffer(not_found,strlen(not_found)));
         }
         socket_.shutdown(boost::asio::socket_base::shutdown_type::shutdown_both);
         handle_write();
     } else {
         delete this;
     }
 }
コード例 #18
0
ファイル: lib.cpp プロジェクト: stephen-soltesz/tester
std::size_t SampleTestClient::recv_data(tcp::socket& socket, int t_length) 
{
    ptime       t1,t2;
    double      tdiff=0;
    double      last_status = 0;

    std::size_t h_recvd=0;
    std::size_t ret=0;

    boost::array<char, DATASIZE>    data;
    boost::system::error_code       error;

    t1 = get_pts();
    t2 = t1;
    h_recvd = 0;

    while ( get_diff(t1,t2) < t_length ) {
        ret = socket.receive(boost::asio::buffer(data), 0, error);
        if ( ret == 0 ) {
            if ( error && error != boost::asio::error::eof) {
                std::cout << error.message() << std::endl;
            }
            break;
        }
        h_recvd += ret;
        t2 = get_pts();
        tdiff = get_diff(t1, t2);
        if ( last_status + 1 < tdiff ) {
            status(tdiff, h_recvd);
            last_status = tdiff;
        }
    }
    status(tdiff, h_recvd);
    return h_recvd;
}
コード例 #19
0
void
controller::listen_for_command()
{
    LOG(INFO) << "Listening for commands...";
    boost::system::error_code error;
    asio::streambuf buffer;

    try
    {
        uint16_t port = global::config()->get("controller.port", 3103);
        tcp::acceptor acceptor(this->io_service_,
                               tcp::endpoint(tcp::v4(), port));

        while (true)
        {
            acceptor.accept(controll_socket_);
            while (true)
            {
                asio::read_until(controll_socket_, buffer, regex("\n"), error);
                if (error)
                    break;

                std::istream is(&buffer);
                string line;
                std::getline(is, line);
                process_command(line);
            }
            controll_socket_.close();
        }
    }
    catch (std::exception& e)
    {
        LOG(ERROR) << e.what();
    }
}
コード例 #20
0
 void
 do_run()
 {
     try
     {
         beast::error_code ec;
         beast::flat_buffer buffer;
         for(;;)
         {
             http::request_parser<http::string_body> parser;
             parser.header_limit(8192);
             parser.body_limit(1024 * 1024);
             http::read(sock_, buffer, parser, ec);
             if(ec == http::error::end_of_stream)
                 break;
             if(ec)
                 throw beast::system_error{ec};
             do_request(parser.get(), ec);
             if(ec)
             {
                 if(ec != http::error::end_of_stream)
                     throw beast::system_error{ec};
                 break;
             }
         }
         sock_.shutdown(tcp::socket::shutdown_both, ec);
         if(ec && ec != boost::asio::error::not_connected)
             throw beast::system_error{ec};
     }
     catch (const std::exception& e)
     {
         std::cerr << "Exception: " << e.what() << std::endl;
     }
 }
コード例 #21
0
ファイル: socket.cpp プロジェクト: LockeLin/WebSocket_server
void L2Socket::HandleAccept( tcp::socket& _socket, boost::system::error_code _ec )
{
    if (!acceptor->is_open() )
    {
        LOG( "HandleAccept acceptor !is_open()!!!" );
        return ;
    }
    if( _ec )
    {
        LOG( "HandleAccept error: "+ _ec.message() );
        Disconnect(_socket);
        return;
    }
    LOG( "HandleAccept New Connect ip: "+_socket.remote_endpoint().address().to_string() + " port: " + _socket.remote_endpoint().port());
    
    //tcp::no_delay option(true);
    //_socket.set_option(option);

    shared_ptr<L2Actor> _act = L2_GET_UNUSED_OBJ(L2Actor);
    
    SERVER->PushActor( _act->OID );
    
    _act->GetAgent()->SetConnect(true);
    sockAry.push_back(&_socket);
    agentOIDAry.push_back( _act->GetAgent()->OID );
    
    if( bWebSocket )
        OnHandshake(_socket,_act->GetAgent()->OID);
    else
        OnReceive( _socket,_act->GetAgent()->OID );
    
    //THREAD->ThreadSleepFPS();
    OnAccept();
}
コード例 #22
0
		~Client()
		{
			try {
				tcp_socket->close();
			} catch (bs::system_error e) {}
			
			delete tcp_socket;
		}
コード例 #23
0
ファイル: echo_server.cpp プロジェクト: mw-ding/DMW-Chat
 void start()
 {
     fprintf(stderr, "session::handle_read()\n");
     socket_.async_read_some(boost::asio::buffer(data_, max_length),
             boost::bind(&session::handle_read, this,
                 boost::asio::placeholders::error,
                 boost::asio::placeholders::bytes_transferred));
 }
コード例 #24
0
void check_deadline(deadline_timer& deadline, tcp::socket& socket) 
{
    if (deadline.expires_at() <= deadline_timer::traits_type::now())
    {
        socket.cancel();
        deadline.expires_at(boost::posix_time::pos_infin);
    }
    deadline.async_wait(boost::bind(&check_deadline, boost::ref(deadline), boost::ref(socket)));
}
コード例 #25
0
void read_handler(const boost::system::error_code &ec,
                  std::size_t bytes_transferred)
{
    if (!ec)
    {
        std::cout.write(bytes.data(), bytes_transferred);
        tcp_socket.async_read_some(buffer(bytes), read_handler);
    }
}
コード例 #26
0
	void handle_accept(tcp::socket &client_socket, const boost::system::error_code& error)
	{

		if (!error &&client_socket.remote_endpoint().address().to_string()!="")
		{
			cout << client_socket.remote_endpoint().address().to_string() + " connected" << endl;
			session_ptr->start();
			session_ptr.reset(new session(g_io_service));
		}
		else
		{
			session_ptr->close_client();
			session_ptr->close_server();
			cout << __FUNCTION__ << "´íÎó£º" << error << endl;
		}

		start_accept();
	}
コード例 #27
0
		Client(int id_given, tcp::socket* tcp_socket_given)
		{
			id = id_given;
			queue = "";
			queue_active = false;
			connected = false;
			active = false;
			broken = false;
			expected_datagram = 0;
			min_fifo_size = max_fifo_size = 0;
			tcp_socket = tcp_socket_given;
			
			try {
				address = tcp_socket->remote_endpoint().address().to_string();
				port = tcp_socket->remote_endpoint().port();
			} catch (bs::system_error e) {
				broken = true;
			}
		}
コード例 #28
0
void connect_handler(const boost::system::error_code &ec)
{
    if (!ec)
    {
        std::string r =
            "GET / HTTP/1.1\r\nHost: theboostcpplibraries.com\r\n\r\n";
        write(tcp_socket, buffer(r));
        tcp_socket.async_read_some(buffer(bytes), read_handler);
    }
}
コード例 #29
0
    void send_file(boost::beast::string_view target)
    {
        // Request path must be absolute and not contain "..".
        if (target.empty() || target[0] != '/' || target.find("..") != std::string::npos)
        {
            send_bad_response(
                http::status::not_found,
                "File not found\r\n");
            return;
        }

        std::string full_path = doc_root_;
        full_path.append(
            target.data(),
            target.size());

        http::file_body::value_type file;
        boost::beast::error_code ec;
        file.open(
            full_path.c_str(),
            boost::beast::file_mode::read,
            ec);
        if(ec)
        {
            send_bad_response(
                http::status::not_found,
                "File not found\r\n");
            return;
        }

        file_response_.emplace(
            std::piecewise_construct,
            std::make_tuple(),
            std::make_tuple(alloc_));

        file_response_->result(http::status::ok);
        file_response_->keep_alive(false);
        file_response_->set(http::field::server, "Beast");
        file_response_->set(http::field::content_type, mime_type(target.to_string()));
        file_response_->body() = std::move(file);
        file_response_->prepare_payload();

        file_serializer_.emplace(*file_response_);

        http::async_write(
            socket_,
            *file_serializer_,
            [this](boost::beast::error_code ec, std::size_t)
            {
                socket_.shutdown(tcp::socket::shutdown_send, ec);
                file_serializer_.reset();
                file_response_.reset();
                accept();
            });
    }
コード例 #30
0
ファイル: cmd.cpp プロジェクト: snyh/WHMon
void CMD_bye::run(tcp::socket& s)
{
  boost::asio::ip::udp::endpoint p;
  p.address(s.remote_endpoint().address());
  p.port(43201);
  vector<Observer>::iterator it = find(observers.begin(), observers.end(),
				       Observer(p, id));
  it->reg(false);
  it->set_id(-1);
  reply(s, "OK BYE");
}