当前位置: 首页>>代码示例>>C++>>正文


C++ tcp::socket类代码示例

本文整理汇总了C++中tcp::socket的典型用法代码示例。如果您正苦于以下问题:C++ socket类的具体用法?C++ socket怎么用?C++ socket使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了socket类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: connectSocket

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);
	}
}
开发者ID:hamling-ling,项目名称:KirinCam,代码行数:25,代码来源:StreamDump.cpp

示例2: handle_connect

	// 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());
		}
	}
开发者ID:dragondgold,项目名称:BrightnessController-Windows,代码行数:30,代码来源:TCPClient.hpp

示例3: echo

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());
 }
}
开发者ID:LocutusOfBorg,项目名称:poedit,代码行数:33,代码来源:double_buffered_echo_server.cpp

示例4: transmit_file

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();
  }
}
开发者ID:barrbrain,项目名称:asio,代码行数:28,代码来源:transmit_file.cpp

示例5: CloseConnection

 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();
   }
 }
开发者ID:gitmesen,项目名称:carla,代码行数:9,代码来源:TCPServer.cpp

示例6: configure

		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.");
			}
		}
开发者ID:sweapon,项目名称:vehicles-ros-pkg,代码行数:9,代码来源:ethernetRelayDriver.hpp

示例7: really_disconnect

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());
	}
}
开发者ID:gogo-dev,项目名称:GoGo,代码行数:10,代码来源:Client.cpp

示例8: Start

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();
}
开发者ID:scp1513,项目名称:cppserver,代码行数:11,代码来源:tcp_server.cpp

示例9: send

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;
    }
}
开发者ID:asimonov-im,项目名称:wesnoth,代码行数:51,代码来源:asio_sender.cpp

示例10: Close

inline bool TCPServerSession::Close()
{
	try
	{
		if (!mSocket.is_open()) return false;
		mSocket.shutdown(socket_base::shutdown_both);
		mSocket.close();
		return true;
	}
	catch (...)
	{
		return false;
	}
}
开发者ID:scp1513,项目名称:cppserver,代码行数:14,代码来源:tcp_server.cpp

示例11: operator

  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)));
  }
开发者ID:boostorg,项目名称:asio,代码行数:29,代码来源:composed_3.cpp

示例12: recvFile

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;
}
开发者ID:lostjared,项目名称:cplusplus11.Examples,代码行数:33,代码来源:filesend.cpp

示例13: send_client

		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));
		}
开发者ID:tomciokotar,项目名称:Sound-Broadcaster,代码行数:7,代码来源:server.cpp

示例14: getResponse

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);
}
开发者ID:DeadHunter,项目名称:TuxNet,代码行数:30,代码来源:main.cpp

示例15: send_bad_response

    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();
            });
    }
开发者ID:miguelportilla,项目名称:Beast,代码行数:29,代码来源:http_server_fast.cpp


注:本文中的tcp::socket类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。