Пример #1
0
void justine::sampleclient::ShmClient::route2 ( boost::asio::ip::tcp::socket & socket, int id )
{

  boost::system::error_code err;

  size_t length = std::sprintf ( data,
                                 "<route 6 %d 1348670117 320900594 1348670109 320900801 651365957 2969934868>", id );

  socket.send ( boost::asio::buffer ( data, length ) );

  length = socket.read_some ( boost::asio::buffer ( data ), err );

  if ( err == boost::asio::error::eof )
    {

      // TODO

    }
  else if ( err )
    {

      throw boost::system::system_error ( err );

    }

  std::cout.write ( data, length );
  std::cout << "Command ROUTE2 sent." << std::endl;

}
Пример #2
0
 void on_connect(boost::asio::ip::tcp::socket &socket) {
     SNOW_LOG_TRACE("new Connection socket fd {}, local addr {}, peer addr {}",
                    socket.native(),
                    socket.local_endpoint(),
                    socket.remote_endpoint());
     std::make_shared<Connection>(socket, m_request_dispatcher, m_pkg_spliter, 100 * 1000)->start();
 }
Пример #3
0
int justine::sampleclient::ShmClient::init ( boost::asio::ip::tcp::socket & socket )
{

  boost::system::error_code err;

  size_t length = std::sprintf ( data, "<init guided Binfavágók 1 c>" );

  socket.send ( boost::asio::buffer ( data, length ) );

  length = socket.read_some ( boost::asio::buffer ( data ), err );

  if ( err == boost::asio::error::eof )
    {

      // TODO

    }
  else if ( err )
    {

      throw boost::system::system_error ( err );

    }

  int id {0};
  std::sscanf ( data, "<OK %d", &id );

  std::cout.write ( data, length );
  std::cout << "Command INIT sent." << std::endl;

  return id;

}
Пример #4
0
void justine::sampleclient::ShmClient::gangsters ( boost::asio::ip::tcp::socket & socket, int id )
{

  boost::system::error_code err;

  size_t length = std::sprintf ( data, "<gangsters " );
  length += std::sprintf ( data+length, "%d>", id );

  socket.send ( boost::asio::buffer ( data, length ) );

  length = socket.read_some ( boost::asio::buffer ( data ), err );

  if ( err == boost::asio::error::eof )
    {

      // TODO

    }
  else if ( err )
    {

      throw boost::system::system_error ( err );
    }

  std::cout.write ( data, length );
  std::cout << "Command GANGSTER sent." << std::endl;

}
				void send()
				{
					BOOST_CHECK_EQUAL( socket_.is_open(), true );
					size_t l = 5;
					socket_.send( boost::asio::buffer( &l, sizeof(size_t) ) );
					socket_.send( boost::asio::buffer( "hello", 5 ) );
				}
Пример #6
0
//===========================================================================
void CHttpClient::DoConnect (
    const boost::system::error_code &        err,
    boost::asio::ip::tcp::resolver::iterator iter
) {
    if (err) {
        if (iter != boost::asio::ip::tcp::resolver::iterator()) {
            m_socket.close();
            boost::asio::ip::tcp::endpoint endPoint = *iter;
            auto handler = boost::bind(
                &CHttpClient::DoConnect,
                this,
                boost::asio::placeholders::error,
                ++iter
            );
            m_socket.async_connect(endPoint, handler);
        } else {
            printf("%s\n", __FUNCTION__);
            cout<<"Error: "<<err.message()<<endl;
        }
        return;
    }

    auto handler = boost::bind(
        &CHttpClient::DoWriteRequest,
        this,
        boost::asio::placeholders::error
    );
    boost::asio::async_write(m_socket, m_request, handler);
}
Пример #7
0
void justine::sampleclient::ShmClient::car ( boost::asio::ip::tcp::socket & socket, int id, unsigned *f, unsigned *t, unsigned* s )
{

  boost::system::error_code err;

  size_t length = std::sprintf ( data, "<car " );
  length += std::sprintf ( data+length, "%d>", id );

  socket.send ( boost::asio::buffer ( data, length ) );

  length = socket.read_some ( boost::asio::buffer ( data ), err );

  if ( err == boost::asio::error::eof )
    {

      // TODO

    }
  else if ( err )
    {

      throw boost::system::system_error ( err );
    }

  int idd {0};
  std::sscanf ( data, "<OK %d %u %u %u", &idd, f, t, s );

  std::cout.write ( data, length );
  std::cout << "Command CAR sent." << std::endl;

}
Пример #8
0
 /** Check that local endpoint is loopback
  *
  *  @throws Face::Error if validation failed
  */
 static void
 validateSocket(boost::asio::ip::tcp::socket& socket)
 {
   if (!socket.local_endpoint().address().is_loopback() ||
       !socket.remote_endpoint().address().is_loopback())
     {
       throw Face::Error("TcpLocalFace can be created only on loopback interface");
     }
 }
std::vector<justine::sampleclient::MyShmClient::Gangster> justine::sampleclient::MyShmClient::gangsters ( boost::asio::ip::tcp::socket & socket, int id,
    osmium::unsigned_object_id_type cop )
{

  boost::system::error_code err;

  size_t length = std::sprintf ( data, "<gangsters " );
  length += std::sprintf ( data+length, "%d>", id );

  socket.send ( boost::asio::buffer ( data, length ) );

  length = socket.read_some ( boost::asio::buffer ( data ), err );

  if ( err == boost::asio::error::eof )
    {

      // TODO

    }
  else if ( err )
    {

      throw boost::system::system_error ( err );
    }

  /* reading all gangsters into a vector */
  int idd {0};
  unsigned f, t, s;
  int n {0};
  int nn {0};
  std::vector<Gangster> gangsters;

  while ( std::sscanf ( data+nn, "<OK %d %u %u %u>%n", &idd, &f, &t, &s, &n ) == 4 )
    {
      nn += n;
      gangsters.push_back ( Gangster {idd, f, t, s} );
    }

  std::sort ( gangsters.begin(), gangsters.end(), [this, cop] ( Gangster x, Gangster y )
  {
    return dst ( cop, x.to ) < dst ( cop, y.to );
  } );

  std::cout.write ( data, length );
  std::cout << "Command GANGSTER sent." << std::endl;

  return gangsters;
}
Пример #10
0
inline connection::~connection()
{
    socket_m.close();
    
    read_thread_m.join();
    send_thread_m.join();
}
Пример #11
0
void server::handle_request(boost::asio::ip::tcp::socket& socket,
	const request& req, reply& rep)
{
	using namespace boost::posix_time;
	
	detail::s_log.reset(new ostringstream);
	ptime start = second_clock::local_time();
	
	try
	{
		handle_request(req, rep);
	}
	catch (...)
	{
		rep = reply::stock_reply(internal_server_error);
	}

	// protect the output stream from garbled log messages
	boost::mutex::scoped_lock lock(detail::s_log_lock);
	cout << socket.remote_endpoint().address()
		 << " [" << start << "] "
		 << second_clock::local_time() - start << ' '
		 << rep.status << ' '
		 << detail::s_log->str() << endl;
}
Пример #12
0
void handler::async_read() {
	auto self(shared_from_this());
	m_socket.async_read_some(boost::asio::buffer(m_buffer),
	                         std::bind(&handler::handle_read, self,
	                                   std::placeholders::_1,
	                                   std::placeholders::_2));
}
Пример #13
0
bool TcpProxyServer::GetRemoteAddressAndPort(boost::asio::ip::tcp::socket& clientSocket, boost::asio::ip::address& remoteAddress, unsigned short& remotePort)
{
	boost::asio::ip::tcp::socket::endpoint_type userAgentEnpoint = clientSocket.remote_endpoint();
    unsigned short userAgentPort = userAgentEnpoint.port();
	boost::asio::ip::address userAgentIP = userAgentEnpoint.address();
	if(userAgentIP != boost::asio::ip::address_v4::from_string("127.0.0.1")) {
		return false;
	}

	std::pair<u_long, USHORT> remoteAddressPair = WinsockHooker::GetRemoteAddressPair(userAgentPort);
	
	if(remoteAddressPair.first == 0ul) {
		return false;
	}

	boost::asio::ip::address_v4 remote_address(remoteAddressPair.first);
	unsigned short remote_port = remoteAddressPair.second;
	if(remote_address == boost::asio::ip::address_v4::from_string("127.0.0.1") && remote_port == listen_port)
	{
		return false;
	}
	remoteAddress = remote_address;
	remotePort = remote_port;

	TSINFO4CXX("Connect: IP:" << remoteAddress.to_string() << ", Port: " << remotePort);
	return true;
}
Пример #14
0
	void start()
	{
		socket_.async_read_some(boost::asio::buffer(data_),
			boost::bind(&session::handle_read, shared_from_this(),
				boost::asio::placeholders::error,
				boost::asio::placeholders::bytes_transferred));
	}
Пример #15
0
static void connected(const boost::system::error_code & ec, boost::asio::ip::tcp::socket & msocket)
{
	if ( ec )
		std::cout <<  ec.message() <<  std::endl;
	else
		msocket.write_some(boost::asio::buffer(std::string("GET / HTTP/1.1\r\n\r\n")));
}
Пример #16
0
 ~WSClientImpl() override
 {
     ws_.close({});
     stream_.close();
     work_ = boost::none;
     thread_.join();
 }
Пример #17
0
bool CPanasonicNode::handleConnect(boost::asio::ip::tcp::socket& socket, boost::asio::ip::tcp::endpoint endpoint, boost::system::error_code& ec)
{
	try
	{
		if (!m_stoprequested)
		{
			socket.connect(endpoint, ec);
			if (!ec)
			{
				if (DEBUG_LOGGING) _log.Log(LOG_NORM, "Panasonic Plugin: (%s) Connected to '%s:%s'.", m_Name.c_str(), m_IP.c_str(), (m_Port[0] != '-' ? m_Port.c_str() : m_Port.substr(1).c_str()));
				return true;
			}
			else
			{
				if (DEBUG_LOGGING)
					if (((ec.value() != 113) && (ec.value() != 111) &&
						(ec.value() != 10060) && (ec.value() != 10061) && (ec.value() != 10064) && (ec.value() != 10061))) // Connection failed due to no response, no route or active refusal
					_log.Log(LOG_NORM, "Panasonic Plugin: (%s) Connect to '%s:%s' failed: (%d) %s", m_Name.c_str(), m_IP.c_str(), (m_Port[0] != '-' ? m_Port.c_str() : m_Port.substr(1).c_str()), ec.value(), ec.message().c_str());
				return false;
			}
		}
	}
	catch (std::exception& e)
	{
		_log.Log(LOG_ERROR, "Panasonic Plugin: (%s) Exception: '%s' connecting to '%s'", m_Name.c_str(), e.what(), m_IP.c_str());
		return false;
	}

	return true;

}
Пример #18
0
void TCPClient::setupSocket(boost::asio::ip::tcp::socket& socket)
{
	if (!_setup_socket)
	{
		_setup_socket = true;
		socket.set_option(boost::asio::ip::tcp::no_delay(true));
	}
}
Пример #19
0
bool server::read_socket_from_parent(int fd_socket, boost::asio::ip::tcp::socket& socket)
{
	typedef boost::asio::ip::tcp::socket::native_type native_type;

#if __APPLE__
	// macos is special...
	assert(CMSG_SPACE(sizeof(int)) == 16);
#endif

	struct msghdr	msg;
	union {
	  struct cmsghdr	cm;
#if __APPLE__
	  char				control[16];
#else
	  char				control[CMSG_SPACE(sizeof(int))];
#endif
	} control_un;

	msg.msg_control = control_un.control;
	msg.msg_controllen = sizeof(control_un.control);
	msg.msg_name = NULL;
	msg.msg_namelen = 0;

	boost::asio::ip::tcp::socket::endpoint_type peer_endpoint;

	struct iovec iov[1];
	iov[0].iov_base = peer_endpoint.data();
	iov[0].iov_len = peer_endpoint.capacity();
	msg.msg_iov = iov;
	msg.msg_iovlen = 1;

	bool result = false;
	int n = recvmsg(fd_socket, &msg, 0);
	if (n >= 0)
	{
		peer_endpoint.resize(n);
	
		struct cmsghdr* cmptr CMSG_FIRSTHDR(&msg);
		if (cmptr != NULL and cmptr->cmsg_len == CMSG_LEN(sizeof(int)))
		{
			if (cmptr->cmsg_level != SOL_SOCKET)
			 	cerr << "control level != SOL_SOCKET" << endl;
			else if (cmptr->cmsg_type != SCM_RIGHTS)
				cerr << "control type != SCM_RIGHTS";
			else
			{
				int fd = *(reinterpret_cast<native_type*>(CMSG_DATA(cmptr)));
				if (fd >= 0)
				{
					socket.assign(peer_endpoint.protocol(), fd);
					result = true;
				}
			}
		}
		else
			cerr << "No file descriptor was passed" << endl;
	}
Пример #20
0
	int Run()
	{
		// ----------- Thread_TcpCommClient_Recv -----------

		int iParam1 = 0;
		pthread_t pthread_TcpCommClient_Recv;
		if(pthread_create(&pthread_TcpCommClient_Recv, NULL, Thread_TcpCommClient_Recv, (void*)this) != 0)
		{
			printf("Failed:Thread_TcpCommClient_Recv\n");
		}
		else
		{
			printf("Initiate:Thread_TcpCommClient_Recv\n");
			usleep(100000);
		}


		// ----------- Thread_TcpCommClient_Send -----------

		int iParam2 = 0;
		pthread_t pthread_TcpCommClient_Send;
		if(pthread_create(&pthread_TcpCommClient_Send, NULL, Thread_TcpCommClient_Send, (void*)this) != 0)
		{
			printf("Failed:Thread_TcpCommClient_Send\n");
		}
		else
		{
			printf("Initiate:Thread_TcpCommClient_Send\n");
			usleep(100000);
		}


		while( ros::ok() )
		{
			ros::spinOnce();
			usleep(30000);
		}

		if( m_Socket.is_open() )
		{
			m_Socket.close();
		}

		return 0;
	}
void do_write(boost::asio::ip::tcp::socket& socket, boost::asio::yield_context yield)
{
    using namespace boost::asio::ip;

    std::time_t now = std::time(0);
    std::string data = std::ctime(&now);
    boost::asio::async_write(socket, boost::asio::buffer(data), yield);
    socket.shutdown(tcp::socket::shutdown_send);
}
Пример #22
0
void run_socket_io(boost::asio::ip::tcp::socket& socket)
{
   std::array<char, 1024> read_buffer;
   std::array<char, 1024> write_buffer;

   socket.async_read_some(boost::asio::buffer(write_buffer, 1024),
       [&write_buffer](const boost::system::error_code& ec, std::size_t length)
       {
          if (!ec)
             std::cout.write(write_buffer.data(), length);
       });

   while (std::cin.getline(read_buffer.data(), 1024))
   {
      socket.send(
          boost::asio::buffer(read_buffer, std::strlen(read_buffer.data())));
   }
}
Пример #23
0
	virtual void send(raw_data& data) {
		bool write_in_progress = !buffer_write_queue_.empty();
		buffer_write_queue_.push_back(data);
		if (!write_in_progress) {
			socket_.async_write_some(
					boost::asio::buffer(buffer_write_queue_.front().bytes, buffer_write_queue_.front().length),
					boost::bind(&session::handle_write, shared_from_this(),
							boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
		}
	}
std::vector<justine::sampleclient::MyShmClient::Cop> justine::sampleclient::MyShmClient::initcops ( boost::asio::ip::tcp::socket & socket )
{

  boost::system::error_code err;

  size_t length = std::sprintf ( data, "<init guided %s 10 c>", m_teamname.c_str() );

  socket.send ( boost::asio::buffer ( data, length ) );

  length = socket.read_some ( boost::asio::buffer ( data ), err );


  if ( err == boost::asio::error::eof )
    {

      // TODO

    }
  else if ( err )
    {

      throw boost::system::system_error ( err );
    }

  /* reading all gangsters into a vector */
  int idd {0};
  int f, t;
  char c;
  int n {0};
  int nn {0};
  std::vector<Cop> cops;

  while ( std::sscanf ( data+nn, "<OK %d %d/%d %c>%n", &idd, &f, &t, &c, &n ) == 4 )
    {
      nn += n;
      cops.push_back ( idd );
    }

  std::cout.write ( data, length );
  std::cout << "Command INIT sent." << std::endl;

  return cops;
}
Пример #25
0
		void	startRead()
		{
			checkNotReading(true);
			 
			reading = true;
			readBuff.ensure_write_space(MAX_READ_BYTES_ONCE);
			socket.async_read_some(boost::asio::buffer(readBuff.wt_ptr(), readBuff.writeable_bytes()),
				boost::bind(&TcpConnection::handleRead, shared_from_this(),
				boost::asio::placeholders::error,
				boost::asio::placeholders::bytes_transferred));
		}
Пример #26
0
void AsyncLoopSocket(boost::function<TaskState()> doWork, boost::asio::ip::tcp::socket& sock, bool isRead)
{
    if (sock.get_io_service().stopped())
    {
        return;
    }

    TaskState st = doWork();

    if (st == TASK_WORKING)
    {
        if (isRead)
        {
            sock.async_read_some(boost::asio::null_buffers(), bind(AsyncLoopSocket, doWork, boost::ref(sock),
                isRead));
        }
        else
        {
            sock.async_write_some(boost::asio::null_buffers(), bind(AsyncLoopSocket, doWork, boost::ref(sock),
                isRead));
        }

        return;
    }

    // Work is over. stop any outstanding events.
    // NOTE: this isn't 100% reliable, and there may be events that linger in the queue.
    // The next time we reset() and run() the io_service, these events will be processed,
    // and io_service::stopped() will return false, because we've just done reset() and run().
    // The state management (SSHSession::State) is our first step in controlling this, and we
    // may need to implement our own cancel mechanism
    //
    // this io_service feature poses an additional problem - by spreading the implementation
    // responsibility across multiple classes, we create scenarios where io_service's queue
    // may contain outstanding events referring to objects that were, in the meantime, destroyed.
    // this is why we're favouring, for now, the use of AsyncLoopTimer, where we can use an
    // io_service for each timer, and destroy it right after being used. this makes sure we
    // process no "zombie" outstanding events.
    sock.get_io_service().stop();
}
Пример #27
0
	inline void connection::handle_write(const boost::system::error_code& e)
	{
	    if (!e) {
		// Initiate graceful connection closure.
		boost::system::error_code ignored_ec;
		socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignored_ec);
	    }

	    // No new asynchronous operations are started. This means that all shared_ptr
	    // references to the connection object will disappear and the object will be
	    // destroyed automatically after this handler returns. The connection class's
	    // destructor closes the socket.
	}
Пример #28
-1
/**
* Вызывается всякий раз, когда данные получены.
*/
static void handleRead(
    ba::ip::tcp::socket&  readFrom,
    ba::ip::tcp::socket&  writeTo,
    char*   readBuffer,
    size_t  bytes,
    const boost::system::error_code&  e
) {
#ifdef _DEBUG
    const std::string  data( readBuffer, readBuffer + bytes );
    std::cout << data << std::endl;
#endif

    // отправляем полученные данные "другой стороне"
    writeTo.send( ba::buffer( readBuffer, bytes ) );

    // читаем ещё данные с "этой стороны"
    readFrom.async_read_some(
        ba::buffer( readBuffer, 1024 ),
        boost::bind(
            handleRead,
            boost::ref( readFrom ),
            boost::ref( writeTo),
            readBuffer,
            ba::placeholders::bytes_transferred,
            ba::placeholders::error
    ) );
}
Пример #29
-1
void justine::sampleclient::ShmClient::pos ( boost::asio::ip::tcp::socket & socket, int id )
{

  boost::system::error_code err;

  size_t length = std::sprintf ( data, "<pos " );
  length += std::sprintf ( data+length, "%d %u %u>", id, 2969934868u, 651365957u );

  socket.send ( boost::asio::buffer ( data, length ) );

  length = socket.read_some ( boost::asio::buffer ( data ), err );

  if ( err == boost::asio::error::eof )
    {

      // TODO

    }
  else if ( err )
    {

      throw boost::system::system_error ( err );

    }

  std::cout.write ( data, length );
  std::cout << "Command POS sent." << std::endl;
}
Пример #30
-1
	inline void connection::start() {
	    socket_.async_read_some(boost::asio::buffer(buffer_),
		    strand_.wrap(
			 boost::bind(&connection::handle_read, shared_from_this(),
				     boost::asio::placeholders::error,
				     boost::asio::placeholders::bytes_transferred)));
	}