Exemplo n.º 1
0
static void server()
{
	ENetEndpoint endpoint(SOCK_STREAM);

	if(endpoint.InitCheck() != E_OK) ETK_ERROR("Failed to create endpoint: %s.", endpoint.ErrorStr());
	if(endpoint.Bind(DEFAULT_PORT) != E_OK) ETK_ERROR("Bind(%d) failed: %s.", DEFAULT_PORT, endpoint.ErrorStr());
	if(endpoint.Listen() != E_OK) ETK_ERROR("Listen() failed: %s.", endpoint.ErrorStr());

	while(true)
	{
		ETK_OUTPUT("Waiting for client ...\n");

		ENetEndpoint *connection = endpoint.Accept(500);
		if(connection == NULL)
		{
			ETK_WARNING("Accept() == NULL: %s.", endpoint.ErrorStr());
			continue;
		}

		struct in_addr addr;
		euint16 port;
		connection->RemoteAddr().GetAddr(addr, &port);

		euint32 ip = E_BENDIAN_TO_HOST_INT32(addr.s_addr);
		ETK_OUTPUT("connection from %d.%d.%d.%d, port: %d\n",
			   ip >> 24, (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff, port);

		EString buf;
		time_t curTime = time(NULL);
		buf << ctime(&curTime) << "\r\n";
		connection->Send(buf.String(), buf.Length());

		delete connection;
	}
}
Exemplo n.º 2
0
void BoostConnection::connect(const HostAddressPort& addressPort) {
	boost::asio::ip::tcp::endpoint endpoint(	
			boost::asio::ip::address::from_string(addressPort.getAddress().toString()), addressPort.getPort());
	socket_.async_connect(
			endpoint,
			boost::bind(&BoostConnection::handleConnectFinished, shared_from_this(), boost::asio::placeholders::error));
}
void Connection::Bind(const std::string & ip, uint16_t port)
{
	boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string(ip), port);
	m_socket.open(endpoint.protocol());
	m_socket.set_option(boost::asio::ip::tcp::acceptor::reuse_address(false));
	m_socket.bind(endpoint);
}
Exemplo n.º 4
0
static void client(const char *address)
{
	ENetEndpoint endpoint(SOCK_STREAM);

	if(endpoint.InitCheck() != E_OK) ETK_ERROR("Failed to create endpoint: %s.", endpoint.ErrorStr());
	if(endpoint.Connect(address, DEFAULT_PORT) != E_OK) ETK_ERROR("Connect() failed: %s.", endpoint.ErrorStr());
	endpoint.SetTimeout(E_INFINITE_TIMEOUT);

	char buf[BUF_SIZE];
	size_t pos = 0;

	bzero(buf, BUF_SIZE);

	while(pos < BUF_SIZE - 1)
	{
		ETK_OUTPUT("Receiving ...\n");

		eint32 bytes = endpoint.Receive(buf + pos, BUF_SIZE - pos - 1);
		if(bytes < 0) break;

		pos += bytes;
		if(pos < 3) continue;

		if(buf[pos - 1] == '\n' && buf[pos - 2] == '\r') break;
	}

	ENetDebug::Enable(true);
	ENetDebug::Dump(buf, pos, "Received");

	ETK_OUTPUT("Received: %s", buf);
}
Exemplo n.º 5
0
void Request::updatePeers(const std::vector<boost::asio::ip::tcp::endpoint>& peers) {
  /* filter the new nodes */
  BOOST_FOREACH(const boost::asio::ip::tcp::endpoint& peer, peers) {
#ifdef GOLD /* for debugging we need to be able to relay back to the origin */
    if (peer == endpoint()) {
      continue;
    }
#endif
    bool seenBefore = false;
    BOOST_FOREACH(const boost::asio::ip::tcp::endpoint& old, peers_) {
      if (peer == old) {
        seenBefore = true;
        break;
      }
    }
    BOOST_FOREACH(const boost::asio::ip::tcp::endpoint& old, peersDone_) {
      if (peer == old) {
        seenBefore = true;
        break;
      }
    }
    if (!seenBefore) {
      peers_.push_back(peer);
    }
  }
}
Exemplo n.º 6
0
void Wall::ShowStructure(QGraphicsScene *c) {

  Vector offset = Cell::Offset();
  double factor = Cell::Factor();

  Vector startpoint ( ((offset.x+n1->x)*factor),((offset.y+n1->y)*factor)),
    endpoint (((offset.x+n2->x)*factor),((offset.y+n2->y)*factor));

  Vector linevec = endpoint - startpoint;
  Vector midline = startpoint + linevec/2.;
  Vector perpvec = linevec.Normalised().Perp2D();
  Vector textpos1 = midline + 100 * perpvec;
  Vector textpos2 = midline - 100 * perpvec;

  QGraphicsLineItem *line = new QGraphicsLineItem(0,c);

  line->setPen( QPen(QColor(par.arrowcolor),2) );
  line->setLine(startpoint.x, startpoint.y, endpoint.x, endpoint.y );
  line->setZValue(10);
  line->show();

  QGraphicsSimpleTextItem *text1 = new QGraphicsSimpleTextItem( QString("%1").arg(c2->Index()),0,c);
  QGraphicsSimpleTextItem *text2 = new QGraphicsSimpleTextItem( QString("%1").arg(c1->Index()),0,c);

  text1 -> setPos( textpos1.x, textpos1.y );
  text2 -> setPos( textpos2.x, textpos2.y );
  text1->setZValue(20); text2->setZValue(20);

  text1->setFont( QFont( "Helvetica", par.nodenumsize, QFont::Bold) );
  text2->setFont( QFont( "Helvetica", par.nodenumsize, QFont::Bold) );

  text1->setPen ( QColor(par.textcolor) );
  text2->setPen ( text1->pen() );
  text1->show(); text2->show();
}
Exemplo n.º 7
0
int main(int argc, char *argv[])
{
    int node_id = 1;
    if (argc == 2)
    {
        node_id = atoi(argv[1]);
    }

    network::IOServiceThreadManager threads(2);
    std::unique_ptr<connector::gw::Client> client;
    asio::ip::tcp::endpoint endpoint(asio::ip::address_v4::from_string("127.0.0.1"), 5150);

    try
    {
        client = std::make_unique<connector::gw::Client>(threads, endpoint, 1, gateway::SvrType::kLoginServer, node_id);
    }
    catch (const std::exception&)
    {
        std::cerr << "连接网关服务器失败!" << std::endl;
        getchar();
        exit(1);
    }
    std::cerr << "连接网关服务器成功!" << std::endl;

    client->set_message_callback([](connector::gw::Client *cli, google::protobuf::Message *msg, network::NetMessage &buf)
    {
    });

    threads.run();

    return 0;
}
Exemplo n.º 8
0
int RTSPServer::Start(unsigned short rtsp_port, std::size_t thread_pool_size)
{

	m_rtspListenPort = rtsp_port;
	m_threadPoolSize = thread_pool_size;

	int iret = -1;
	try
	{
		boost::asio::ip::tcp::endpoint endpoint(
			boost::asio::ip::tcp::v4(), m_rtspListenPort);
		m_acceptor_.open(endpoint.protocol());
		m_acceptor_.bind(endpoint);
		m_acceptor_.listen();

		StartAccpet();
		m_bStoped = false;
		iret = 0;
	}
	catch (std::exception& e)
	{
		std::cerr << e.what() << std::endl;
	}

	return iret;
}
Exemplo n.º 9
0
void listener_loop(int port_number)
{
	boost::thread workerThread3(updateMeasurement);
	

	boost::asio::io_service io_service;
	boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::tcp::v4(), port_number);
	boost::asio::ip::tcp::acceptor acceptor(io_service, endpoint);

	
	while(true)
	{
		try
		{

			boost::shared_ptr<boost::asio::ip::tcp::socket> socket = boost::make_shared<boost::asio::ip::tcp::socket>(boost::ref(io_service));
			established_connections.push_back(socket);
			std::cout << "TCP server ready and listening ... " << std::endl;
			acceptor.accept(*established_connections.back());
			std::cout << "Number of established client connections: ";
			std::cout << established_connections.size() << std::endl;
			
			boost::thread workerThread2(worker,established_connections.back());
			
		}
		catch(std::exception& e)
		{
			std::cerr << "Exception: " << e.what() << std::endl;
		}
	}
}
Exemplo n.º 10
0
IPCServer::IPCServer( const std::string & path,
                      const std::size_t worker_pool_size )
	: ServiceServer( worker_pool_size ),
	  new_connection_(),
	  acceptor_( io_service_ )
{
	unlink( path.c_str() );

	try {
		asio::local::stream_protocol::endpoint endpoint( path );

		acceptor_.open( endpoint.protocol() );
		acceptor_.bind( endpoint );
		acceptor_.listen();

	} catch( boost::system::system_error & e ) {
		throw( new IPCServerException( "Unable to create IPC server." ) );
	}

	try {
		start_accept();
	} catch( IPCServerException & ipc_e ) {
		throw;
	}

#ifndef NDEBUG
	logger->log( Logger::DEBUG, "IPC server created and accepting connections." );
#endif
}
Exemplo n.º 11
0
void RedisAsyncClient::connect(const boost::asio::ip::address &address,
                               unsigned short port,
                               std::function<void(bool, const std::string &)> handler)
{
    boost::asio::ip::tcp::endpoint endpoint(address, port);
    connect(endpoint, std::move(handler));
}
Exemplo n.º 12
0
int main(int argc, char *argv[])
{
    boost::asio::io_service io;
    boost::asio::ip::udp::endpoint endpoint(boost::asio::ip::udp::v4(), 12346);
    server s(io, endpoint);
    io.run();
    return 0;
}
Exemplo n.º 13
0
void NoeudThor::startConnectSecureNodeListProvider()
{
	noeudSecureNodeListProvider = new Client<NoeudThor>(this, io_service);
	tcp::endpoint endpoint(boost::asio::ip::address::from_string(ipSecureNodeListProvider), portSecureNodeListProvider);
	cout << "Connection au Secure Node List Provider" << std::endl;
	noeudSecureNodeListProvider->getSocket().connect(endpoint);
	noeudSecureNodeListProvider->startRead();
}
Exemplo n.º 14
0
void NoeudThor::startConnectServeurCentral()
{
	noeudServeurCentral = new Client<NoeudThor>(this, io_service);
	tcp::endpoint endpoint(boost::asio::ip::address::from_string(ipServeurCentral), portServeurCentral);
	cout << "Connection au serveur central" << std::endl;
	noeudServeurCentral->getSocket().connect(endpoint);
	noeudServeurCentral->startRead();
}
Exemplo n.º 15
0
bool TajoSyncClient::connect(const boost::asio::ip::address &address,
        unsigned short port,
        std::string &errmsg)
{
    tcp::endpoint endpoint(address, port);

    return connect(endpoint, errmsg);
}
Exemplo n.º 16
0
udp::endpoint StringToEndpoint(const string &strIpPort)
{
	char szIp[16] = {0};
	unsigned int dwPort;
	sscanf(strIpPort.c_str(), "%[^:]:%d", szIp, &dwPort);
	udp::endpoint endpoint(boost::asio::ip::address::from_string(szIp), dwPort);
	return endpoint;
}
Exemplo n.º 17
0
void acceptors_list<Connection>::start_acceptor(size_t index)
{
	acceptor_type &acc = *acceptors[index];

	auto conn = std::make_shared<connection_type>(data.server, get_connection_service(), data.buffer_size);

	acc.async_accept(conn->socket(), conn->endpoint(), boost::bind(
				 &acceptors_list::handle_accept, this, index, conn, _1));
}
//---------------------------------------------------------------------------
// The most siginificant method of this class. 
//---------------------------------------------------------------------------
//
TInt CWSStarHttpClient::GetHttpL( const TDesC8& aRequest,
                                  HBufC8*& apResponse,
                                  CSenWSDescription* apSD )
    {
    TLSLOG_L(KSenCoreServiceManagerLogChannelBase  , KMinLogLevel,"CWSStarHttpClient::GetHttpL");
    TInt retVal(KErrNone);             // for returning error codes
    if( !iInitializer )
        {
        return KErrSenInternal;
        }
    TPtrC8 endpoint(iInitializer->Endpoint());    

    CSenHttpTransportProperties* pHttpProperties = CSenHttpTransportProperties::NewLC();
    pHttpProperties->SetHttpMethodL(CSenHttpTransportProperties::ESenHttpGet);
    _LIT8(KAcceptedHeader, "text/xml,text/plain");    
    pHttpProperties->SetAcceptL(KAcceptedHeader);
    TUint32 desiredIapId(0);
   
    if( apSD )
        {
        TInt getIapRetVal = apSD->IapId( desiredIapId );
        if ( getIapRetVal == KErrNone )
            {
            pHttpProperties->SetIapIdL( desiredIapId );
            }
        }
     //limit http timeout, 
	pHttpProperties->SetMaxTimeToLiveL(WSStarSession::KMaxHttpTimeOut);
	TLSLOG_FORMAT((KSenCoreServiceManagerLogChannelBase  , KNormalLogLevel, _L8("CWSStarHttpClient::GetHttpL - with IAP ID (%d):"), desiredIapId));    
    HBufC8* pSerializedProperties  = pHttpProperties->AsUtf8L();
    CleanupStack::PopAndDestroy(pHttpProperties);

    CleanupStack::PushL(pSerializedProperties);
    TLSLOG_ALL(KSenCoreServiceManagerLogChannelBase  , KNormalLogLevel,( pSerializedProperties->Des() ));
    retVal = ipTransport->SubmitL(endpoint, aRequest, *pSerializedProperties, apResponse, *this);	
    TLSLOG_FORMAT((KSenCoreServiceManagerLogChannelBase  , KNormalLogLevel, _L8("CWSStarHttpClient::GetHttpL - SubmitL returned: %d"), retVal));    

    CleanupStack::PopAndDestroy( pSerializedProperties );

#ifdef _SENDEBUG
    if( apResponse )
        {
        TPtrC8 response = apResponse->Des();
        TLSLOG_L(KSenCoreServiceManagerLogChannelBase  , KMaxLogLevel,"* * * * * * * * * * * * *");
        TLSLOG_FORMAT((KSenCoreServiceManagerLogChannelBase  , KMaxLogLevel, _L8("CWSStarHttpClient::GetHttpL - response (%d bytes):"), response.Length()));    
        TLSLOG_ALL(KSenCoreServiceManagerLogChannelBase  , KMaxLogLevel,( response ));
        TLSLOG_L(KSenCoreServiceManagerLogChannelBase  , KMinLogLevel,"CSenCoreServiceManager::CreateL:");
        }
#endif // _SENDEBUG        

    if( retVal != KErrNone )
        {
        delete apResponse; 
        apResponse = NULL;
        }
    return retVal;
    }
		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.");
			}
		}
Exemplo n.º 20
0
int AMHS_Server::Start(int nPort)
{
	tcp::endpoint endpoint(tcp::v4(), nPort);
	amhs_dev_server* DevServer = new amhs_dev_server(m_io_service, endpoint);
	m_pServer = amhs_server_ptr(DevServer);
	m_thread = boost::thread(boost::bind(&boost::asio::io_service::run, &m_io_service));

	return 0;
}
Exemplo n.º 21
0
void Provider::fetch(const Request &request)
{
    QUrl requestUrl(endpoint());
    requestUrl.setQuery(request.createQuery());

//    qDebug() << request.url() << requestUrl;

    d->manager->get(QNetworkRequest(requestUrl));
}
Exemplo n.º 22
0
std::uint16_t testing::util::port() {
    boost::asio::io_service loop;
    boost::asio::ip::tcp::acceptor acceptor(loop);
    boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::tcp::v4(), 0);
    acceptor.open(endpoint.protocol());
    acceptor.bind(endpoint);
    acceptor.listen();
    return acceptor.local_endpoint().port();
}
Exemplo n.º 23
0
void KeyframeMapper::buildColorOctomap(octomap::ColorOcTree& tree)
{
  ROS_INFO("Building Octomap with color...");

  octomap::point3d sensor_origin(0.0, 0.0, 0.0);  

  for (unsigned int kf_idx = 0; kf_idx < keyframes_.size(); ++kf_idx)
  {
    ROS_INFO("Processing keyframe %u", kf_idx);
    const rgbdtools::RGBDKeyframe& keyframe = keyframes_[kf_idx];
       
    // construct the cloud
    PointCloudT::Ptr cloud_unf(new PointCloudT());
    keyframe.constructDensePointCloud(*cloud_unf, max_range_, max_stdev_);
  
    // perform filtering for max z
    pcl::transformPointCloud(*cloud_unf, *cloud_unf, keyframe.pose);
    PointCloudT cloud;
    pcl::PassThrough<PointT> pass;
    pass.setInputCloud (cloud_unf);
    pass.setFilterFieldName ("z");
    pass.setFilterLimits (-std::numeric_limits<double>::infinity(), max_map_z_);
    pass.filter(cloud);
    pcl::transformPointCloud(cloud, cloud, keyframe.pose.inverse());
    
    octomap::pose6d frame_origin = poseTfToOctomap(tfFromEigenAffine(keyframe.pose));
    
    // build octomap cloud from pcl cloud
    octomap::Pointcloud octomap_cloud;
    for (unsigned int pt_idx = 0; pt_idx < cloud.points.size(); ++pt_idx)
    {
      const PointT& p = cloud.points[pt_idx];
      if (!std::isnan(p.z))
        octomap_cloud.push_back(p.x, p.y, p.z);
    }
    
    // insert scan (only xyz considered, no colors)
    tree.insertScan(octomap_cloud, sensor_origin, frame_origin);
    
    // insert colors
    PointCloudT cloud_tf;
    pcl::transformPointCloud(cloud, cloud_tf, keyframe.pose);
    for (unsigned int pt_idx = 0; pt_idx < cloud_tf.points.size(); ++pt_idx)
    {
      const PointT& p = cloud_tf.points[pt_idx];
      if (!std::isnan(p.z))
      {
        octomap::point3d endpoint(p.x, p.y, p.z);
        octomap::ColorOcTreeNode* n = tree.search(endpoint);
        if (n) n->setColor(p.r, p.g, p.b); 
      }
    }
    
    tree.updateInnerOccupancy();
  }
}
Exemplo n.º 24
0
void TcpServer::createServer(int port, int)
{
    tcp::endpoint endpoint(tcp::v4(), port);
    mPort = port;
    mAcceptor = boost::shared_ptr<tcp::acceptor>(new tcp::acceptor(mService, endpoint));
    std::cout << "[TCP] start listening on port " << port << std::endl;
    startAccept();
    boost::system::error_code ec;
    mService.run(ec);
}
Exemplo n.º 25
0
void
AircraftSim::integrate(const Angle& heading, const fixed timestep)
{
  GeoPoint v = endpoint(heading, timestep);
  state.track = state.location.bearing(v);
  state.ground_speed = v.distance(state.location)/timestep;
  state.location = v;
  state.altitude += state.vario*timestep;
  state.time += timestep;
}
Exemplo n.º 26
0
void Rcon::Reconnect(const boost::system::error_code& error)
{
	logger->info("Rcon: Attempting to Reconnect");
	boost::asio::ip::udp::endpoint endpoint(boost::asio::ip::address::from_string(rcon_settings.address), rcon_settings.port);

	{
		std::lock_guard<std::mutex> lock(rcon_socket.mutex);
		rcon_socket.socket->async_connect(endpoint, boost::bind(&Rcon::connectionHandler, this, boost::asio::placeholders::error));
	}
}
Exemplo n.º 27
0
bool TcpProxyServer::Bind(boost::asio::ip::address address, unsigned short listen_port)
{
	this->listen_port = listen_port;
	if(!this->acceptor.is_open()) {
		return false;	
	}
	boost::asio::ip::tcp::acceptor::endpoint_type endpoint(address, listen_port);
	boost::system::error_code ec;
	this->acceptor.bind(endpoint, ec);
	return !ec;
}
Exemplo n.º 28
0
    std::string address() const {
        if (endpoint_.address().is_v6()) {
            std::string result;
            result.push_back('[');
            result.append(endpoint().address().to_string());
            result.push_back(']');
            return result;
        }

        return endpoint_.address().to_string();
    }
Exemplo n.º 29
0
typename acceptors_list<Connection>::endpoint_type acceptors_list<Connection>::create_endpoint(acceptor_type &acc, const std::string &host)
{
	(void) acc;

	size_t delim = host.find_last_of(':');
	auto address = boost::asio::ip::address::from_string(host.substr(0, delim));
	auto port = boost::lexical_cast<unsigned short>(host.substr(delim + 1));

	boost::asio::ip::tcp::endpoint endpoint(address, port);

	return endpoint;
}
Exemplo n.º 30
0
	void host::ssl_bind_to(short port)
	{
		boost::asio::ip::tcp::endpoint endpoint(asio::ip::tcp::v4(), port);
		ssl_acceptor_.open(asio::ip::tcp::v4());
		ssl_acceptor_.bind(endpoint);
		ssl_acceptor_.listen();
	
		server::ssl_connection_ptr new_connection(new server::ssl_connection(*this, *context_));	
		ssl_acceptor_.async_accept(new_connection->socket(),
			boost::bind(&host::ssl_handle_accept, this, new_connection,
			boost::asio::placeholders::error));		
	}