Exemple #1
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;
		}
	}
}
		void do_accept(
			const std::string address,
			const std::string port,
			const boost::asio::yield_context& yield)
		{
			LOG_DBG << "Listen on " << address << ":" << port;
			boost::asio::ip::tcp::acceptor acceptor(io_service_pool_.get_io_service());
			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();

			for (;;)
			{
				auto conn(
					std::make_shared<Connection<tcp_socket>>(
					io_service_pool_.get_io_service(),
					request_handler_, error_handler_, static_dir_));

				boost::system::error_code ec;
				acceptor.async_accept(conn->raw_socket(), yield[ec]);
				if (ec)
				{
					LOG_DBG << "Accept new connection failed: " << ec.message();
					continue;
				}

				conn->start();
			}
		}
Exemple #3
0
	static void receive()
	{
		//³õʼ»¯socket
		ASIO::io_service iosev;
		ASIO::ip::tcp::acceptor acceptor(iosev, ASIO::ip::tcp::endpoint(ASIO::ip::tcp::v4(), (unsigned int)port));
		ASIO::ip::tcp::socket socket(iosev);
		acceptor.accept(socket);
		ofs.open("ofstream.log", std::ios::out);
		ofs << " client from " << socket.remote_endpoint().address() << std::endl;
		boost::system::error_code ec;
		char buf[BLOCK_SIZE];
		int step = 0;
		for (;;)
		{
			int len = socket.read_some(ASIO::buffer(buf), ec);
			if (!start)
				return ;
			if (ec)
			{
				ofs << "error"
					<<boost::system::system_error(ec).what() << std::endl;
				break;
			}
			ofs.write(buf, len);
			ofs << "len =" << len << std::endl;
			ofs <<"step"<< ++step << std::endl;
			//½ÓÊÕ
			Sleep(1000);
		}
		ofs.close();
	}
Exemple #4
0
void Device::server_run()
{
	try {
		/* starts thread that responds to discovery requests */
		ServerDiscovery discovery;

		for(;;) {
			/* accept connection */
			boost::asio::io_service io_service;
			tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), SERVER_PORT));

			tcp::socket socket(io_service);
			acceptor.accept(socket);

			string remote_address = socket.remote_endpoint().address().to_string();
			printf("Connected to remote client at: %s\n", remote_address.c_str());

			DeviceServer server(this, socket);
			server.listen();

			printf("Disconnected.\n");
		}
	}
	catch(exception& e) {
		fprintf(stderr, "Network server exception: %s\n", e.what());
	}
}
/**
 * Listening and handling incoming requests
 */
void HttpServer::listen()
{

    try
    {
        // Start server
        boost::asio::io_service io_service;
        tcp::endpoint localhost(tcp::v4(), this->port);
        tcp::acceptor acceptor(io_service, localhost);

        std::cout << "Server has started. Listening on address localhost:" << this->port 
            << " (that's 127.0.0.1:" << this->port << " for you Windows folks).\n\n"
            << "Now type this address into your browser." << std::endl;

        // Reply to incoming HTTP requests
        while (1)
        {
            boost::system::error_code error_code;
            
            // Accept connection
            tcp::socket socket(io_service);
            acceptor.accept(socket);

            // Send HTTP response
            std::string filepath = parse_request(socket, error_code);
            boost::asio::write(socket, boost::asio::buffer(build_response(filepath)), error_code);
        }
    }
    catch (std::exception& e)
    {
        std::cerr << e.what() << std::endl;
    }
}
Exemple #6
0
void select_interrupter::open_descriptors()
{
    xxsocket acceptor(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    acceptor.set_optval(SOL_SOCKET, SO_REUSEADDR, 1);

    ip::endpoint ep("127.0.0.1", 0);

    acceptor.bind(ep);
    ep = acceptor.local_endpoint();
    // Some broken firewalls on Windows will intermittently cause getsockname to
    // return 0.0.0.0 when the socket is actually bound to 127.0.0.1. We
    // explicitly specify the target address here to work around this problem.
    // addr.sin_addr.s_addr = socket_ops::host_to_network_long(INADDR_LOOPBACK);
    // cp.address("127.0.0.1");
    ep.address("127.0.0.1");
    acceptor.listen();

    xxsocket client(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    client.connect(ep);

    auto server = acceptor.accept();

    client.set_nonblocking(true);
    client.set_optval(IPPROTO_TCP, TCP_NODELAY, 1);

    server.set_nonblocking(true);
    client.set_optval(IPPROTO_TCP, TCP_NODELAY, 1);

    read_descriptor_ = server.release();
    write_descriptor_ = client.release();
}
Exemple #7
0
int main(int argc, char* argv[])
{
   if (argc != 5)
   {
      std::cerr << "usage: tcpproxy_server <local host ip> <local port> <remote host ip> <remote port>" << std::endl;
      return 1;
   }

   const unsigned short local_port  = static_cast<unsigned short>(::atoi(argv[2]));
   const unsigned short remote_port = static_cast<unsigned short>(::atoi(argv[4]));
   const std::string local_host     = argv[1];
   const std::string remote_host    = argv[3];

   boost::asio::io_service ios;

   try
   {
      tcp_proxy::tcp_bridge::acceptor acceptor(ios,
                                               local_port,remote_port,
                                               local_host,remote_host);
      acceptor.accept_connections();
      ios.run();
   }
   catch(std::exception& e)
   {
      std::cerr << e.what() << std::endl;
      return 1;
   }

   return 0;
}
Exemple #8
0
int main(int, char**) {
    try {
        boost::asio::io_context ios;
        easynet::acceptor acceptor(ios, tests_config::ip, tests_config::port);

        while ( true ) {
            char buf[tests_config::buffer_size] = "\0";
            easynet::endpoint ep;
            easynet::error_code ec;

            easynet::socket socket(ios);
            acceptor.accept(socket, ec, &ep);

            std::cout << "new connection from " << ep << ", ec = " << ec << std::endl;
            if ( !ec ) {
                socket.read(buf, tests_config::buffer_size, ec);
                if ( !ec ) {
                    socket.write(buf, tests_config::buffer_size, ec);
                } else {
                    std::cout << "[1] ec = " << ec << std::endl;
                }
            } else {
                std::cout << "[2] ec = " << ec << std::endl;
            }
        }
    } catch (const std::exception &ex) {
        std::cout << "[exception]: " << ex.what() << std::endl;
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}
Exemple #9
0
int main(int argc, char** argv)
{
	if (argc != 2)
	{
		printf("usage: binary_name port\n");
		return -1;
	}

	tool::net_start();

	std::vector<chat::channel*> rooms;
	rooms.push_back(new chat::channel());

	tool::acceptor acceptor(argv[1]);

	printf("listening on port %s\n", argv[1]);

	while (true)
	{
		std::shared_ptr<chat::user> user = accept_user(acceptor);
		rooms.at(0)->add_user(user);
	}

	tool::net_stop();
	return 0;
}
int Iterative_Server::run()
{
	int retsock;
	if( (retsock=init())<=0)
	{
		outerr("server init error, exit");
		exit(0);
	}

	fprintf(stdout, "the server run:\n");

	
	SocketStream ss;
	for(;;)
	{

		acceptor(retsock,ss);
		if(waitfor_multievent()==-1)
			return -1;
		if(handleConnection()==-1)
			return -1;
		if(handleData(ss)==-1)
			return -1;
	}




}
Exemple #11
0
/*
 * Sets up listening for and accepting subs
 *  - @port: the communication port on localhost
 */
void Communication::Accept(std::string port)
{
    boost::shared_ptr<boost::asio::ip::tcp::acceptor> acceptor(new boost::asio::ip::tcp::acceptor(*io_service_));
    boost::shared_ptr<boost::asio::ip::tcp::socket> sock(new boost::asio::ip::tcp::socket(*io_service_));

    acceptor_ = acceptor;

    try
    {
        boost::asio::ip::tcp::resolver resolver(*io_service_);
        boost::asio::ip::tcp::resolver::query query("127.0.0.1", 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(boost::asio::socket_base::max_connections);

        std::cout << "[" << boost::this_thread::get_id()
                  << "] Listening on: " << endpoint << std::endl;

        acceptor_->async_accept(*sock, boost::bind(&Communication::AddClient,
                                                   this,
                                                   boost::asio::placeholders::error(),
                                                   sock));
    }

    // report any exceptions
    catch (std::exception & ex)
    {
        std::cout << "[" << boost::this_thread::get_id()
                  << "] Exception: " << ex.what() << std::endl;
    }
}
Exemple #12
0
int main( ) try
{

    ba::io_service       ios;
    ba::io_service::work wrk(ios);

    ba::ip::tcp::acceptor acceptor( ios, make_endpoint("0.0.0.0", 55555) );

    start_accept( acceptor );

//    boost::thread t1( run_ios, boost::ref( ios ) );
//    boost::thread t2( run_ios, boost::ref( ios ) );
//    boost::thread t3( run_ios, boost::ref( ios ) );
//    boost::thread t4( run_ios, boost::ref( ios ) );

    run_ios( ios );

    return 0;

} catch( const std::exception &ex ) {

    std::cout << "main error: " << ex.what( ) << "\n";
    return 1;

}
int main()
{
	try
	{
		///////////////////////////////////////////
		const int port=50013;
		boost::asio::io_service		io_service;
		boost::asio::ip::tcp::endpoint	endpoint(boost::asio::ip::tcp::v4(), port);
		boost::asio::ip::tcp::acceptor	acceptor(io_service, endpoint);
		boost::asio::ip::tcp::socket	socket(io_service);
		///////////////////////////////////////////
		std::cout<<"Server listening on port ["<<port<<"]..."<<std::endl;
		acceptor.accept(socket); //blocking
		std::string message("ping ping ping\n");
		boost::asio::write(socket, boost::asio::buffer(message));
		//or
		//socket.write_some(boost::asio::buffer(message));
		socket.close();
		///////////////////////////////////////////
	}
	catch(std::exception& e)
	{
		std::cerr<<"Exception: "<<e.what()<<std::endl;
	}
}
Exemple #14
0
    void SyncServer::startSync(asio::io_service& io) {
        while(1) {
            asio::ip::tcp::socket socket(io);
            asio::ip::tcp::acceptor acceptor(io, endpoint);
            acceptor.accept(socket);
            std::string data = "";
            while(1) {
                auto instance = SendDataManager::getInstance();

                if(instance.first->hasNewData()){
                    data = instance.first->serializeShallow();
                    instance.second.unlock();
                    try {
                        asio::write(socket, asio::buffer(data), asio::transfer_all());
                    } catch(std::system_error&){
                        std::cerr << "Synthesis warning: Sender socket disconnected. User code will continue to run.\n";
                        break;
                    }
                } else {
                    instance.second.unlock();
                }
                usleep(30000);
            }
        }
    }
Exemple #15
0
int main( int argc, char** argv )
{
  if ( argc != 2 )
  {
    std::cout << "usage: " << argv[ 0 ]
    << " FILE." << std::endl;
    return 0;
  }
  std::string file = argv[ 1 ];

  try
  {
    FIX::SessionSettings settings( file );

    Application application;
    FIX::FileStoreFactory storeFactory( settings );
    FIX::ScreenLogFactory logFactory( settings );
    FIX::ThreadedSocketAcceptor acceptor( application, storeFactory, settings, logFactory );

    acceptor.start();
    wait();
    acceptor.stop();
    return 0;
  }
  catch ( std::exception & e )
  {
    std::cout << e.what() << std::endl;
    return 1;
  }
}
Exemple #16
0
USING_NAMESPACE

int main()
{
	Acceptor acceptor(InterAddress(6000, "127.0.0.1"));

	while (1)
	{
		Stream newStream;
		char   buf[100];
		int nDataSize = 0;

		if (acceptor.accept(TimeValue(1), newStream))
		{
			char szIp[20]; int32 nPort;
			newStream.getRemoteAddress(szIp, nPort);

			printf("connected from [%s:%d]\n", szIp, nPort);

			if ((nDataSize = newStream.recv(buf, 100)) > 0)
			{
				buf[nDataSize] = '\0';
				printf("recv from [%s:%d] content : %s\n", szIp, nPort, buf);

				newStream.send(buf, nDataSize);
			}
		}
		else
		{
			printf("acceptor time out!!!!\n");
		}
	}

	return 0;
}
Exemple #17
0
void Connector::connectorThread( void ) {
	printf( "[Connector (%p)] Connector thread started: mode=%d\n",
		this, _isServer );

	if (_isServer) {
		AcceptorPtr acceptor(new Acceptor(_io, getEndpoint()));
		acceptor->async_accept(*_socket,
		    boost::bind(&Connector::handle_accept, this, acceptor, 
				    boost::asio::placeholders::error));

		    //	Launch timer ....
		    launchTimer( _acceptTimer, _connectTimeout, &Connector::onAcceptExpired );
	} else {
		_socket->async_connect(getEndpoint(),
			boost::bind(&Connector::handle_connect, this,
				boost::asio::placeholders::error));
	}

	try {
		_io.run();
	}
	catch (std::exception& e) {
		printf( "[Connector (%p)] Exception: %s\n", this, e.what() );
	}

	disconnected();
	printf( "[Connector (%p)] Info: Connector Thread Stopped\n", this );
}
Exemple #18
0
long testSendOnThreadedSocket( int count, short port )
{
  std::stringstream stream;
  stream
    << "[DEFAULT]" << std::endl
    << "SocketConnectHost=localhost" << std::endl
    << "SocketConnectPort=" << (unsigned short)port << std::endl
    << "SocketAcceptPort=" << (unsigned short)port << std::endl
    << "SocketReuseAddress=Y" << std::endl
    << "StartTime=00:00:00" << std::endl
    << "EndTime=00:00:00" << std::endl
    << "UseDataDictionary=N" << std::endl
    << "BeginString=FIX.4.2" << std::endl
    << "PersistMessages=N" << std::endl
    << "[SESSION]" << std::endl
    << "ConnectionType=acceptor" << std::endl
    << "SenderCompID=SERVER" << std::endl
    << "TargetCompID=CLIENT" << std::endl
    << "[SESSION]" << std::endl
    << "ConnectionType=initiator" << std::endl
    << "SenderCompID=CLIENT" << std::endl
    << "TargetCompID=SERVER" << std::endl
    << "HeartBtInt=30" << std::endl;

  FIX::ClOrdID clOrdID( "ORDERID" );
  FIX::HandlInst handlInst( '1' );
  FIX::Symbol symbol( "LNUX" );
  FIX::Side side( FIX::Side_BUY );
  FIX::TransactTime transactTime;
  FIX::OrdType ordType( FIX::OrdType_MARKET );
  FIX42::NewOrderSingle message( clOrdID, handlInst, symbol, side, transactTime, ordType );

  FIX::SessionID sessionID( "FIX.4.2", "CLIENT", "SERVER" );

  TestApplication application;
  FIX::MemoryStoreFactory factory;
  FIX::SessionSettings settings( stream );

  FIX::ThreadedSocketAcceptor acceptor( application, factory, settings );
  acceptor.start();

  FIX::ThreadedSocketInitiator initiator( application, factory, settings );
  initiator.start();

  FIX::process_sleep( 1 );

  long start = GetTickCount();
  for ( int i = 0; i <= count; ++i )
    FIX::Session::sendToTarget( message, sessionID );

  while( application.getCount() < count )
    FIX::process_sleep( 0.1 );

  long ticks = GetTickCount() - start;

  initiator.stop();
  acceptor.stop();

  return ticks;
}
Exemple #19
0
boost::asio::ip::tcp::socket listen_socket(boost::asio::io_service& io_service,
    char* port, boost::system::error_code& ec)
{
   boost::asio::ip::tcp::acceptor acceptor(io_service);
   boost::asio::ip::tcp::socket socket(io_service);
   acceptor.accept(socket, ec);
   return socket;
}
int main(int argc, char** argv)
{
    // command arguments
    if ( argc < 2 || 3 < argc ) {
        std::cerr << "usage: " << argv[0] << " <games> [<port>]" << std::endl;
        return -1;
    }

    // games threads
    unsigned int games = std::stoi(argv[1]);

      // common queue
    SharedQueue<PointersStack<Stream>* > queue;

    MultiThread mth;

    for (unsigned int i = 0; i < games; ++i)
        mth.create(function_thread, std::ref(queue));
    

    
    // acceptor
    unsigned int port;
    if (argc == 3)
        port = std::stoi(argv[2]);
    else
        port = PORT;

    
    Acceptor acceptor(port);

    if (acceptor.start() != 0) {
        std::cerr << "error: starting acceptor" << std::endl;
        return -1;
    }

    // main loop
    for (;;) {

        Stream* connection0;
        do {
            connection0 = acceptor.accept();
        } while (connection0 == NULL);
        std::cout << "Server: connection 1 of 2 accepted" << std::endl;

        Stream* connection1;
        do {
            connection1 = acceptor.accept();
        } while (connection1 == NULL);
        std::cout << "Server: connection 2 of 2 accepted" << std::endl;

        queue.add(new PointersStack<Stream> (connection0, connection1));
        
    }


    return 0;
}
Exemple #21
0
	void run_file_server(boost::uint16_t port,
						 boost::shared_ptr<directory> directory)
	{
		boost::asio::io_service io_service;
		tcp_acceptor acceptor(port,
							  boost::bind(handle_client, _1, directory),
							  io_service);
		io_service.run();
	}
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();
}
Exemple #23
0
int main(int argc, char* argv[])
{
  setlocale(LC_ALL, "");

  settings setting;
  try {
    if (!setting.load(argc, argv)) {
      return 0;
    }
  }
  catch (const boost::property_tree::ptree_error& error) {
    std::cerr << "Error: " << error.what() << std::endl;
    return 1;
  }
  catch (const boost::program_options::error& error) {
    std::cerr << "Error: " << error.what() << std::endl;
    return 1;
  }
  catch (const std::exception& error) {
    std::cerr << "Error: " << error.what() << std::endl;
    return 1;
  }

  print_setting(setting);

  if (setting.log_filename.size() != 0 && 
      !boost::filesystem::exists(setting.log_filename)) {
    std::cerr << "Log file path error " + setting.log_filename;
    setting.log_filename = "logs/" + setting.section + ".log";
  }

  init_log(setting.log_level, setting.log_filename);

  boost::asio::io_service ios;

  try {
    acceptor acceptor(ios, setting.local.host, setting.local.port,
                      setting.remote.host, setting.remote.port,
                      setting.cn,
                      certs_path(setting.cert_filename,
                      setting.key_filename,
                      setting.dh_filename));
    BLOG(info) << "accept connections on " 
               << setting.local.host << ":" << setting.local.port 
               << ", remote host " 
               << setting.remote.host << ":" << setting.remote.port;
    acceptor.accept_connections();
    ios.run();
  }
  catch(std::exception& e) {
    std::cerr << std::string("Error: ") + e.what() << std::endl;
    return 1;
  }

  return 0;
}
TEST_F(HandshakeTest, RecvFail) {
  class Contestador_Fail: public Contestador {
    public: const char* get_msg(){ return "Garbage"; }
  };

  MockDb db;
  ACE_Acceptor<Contestador_Fail, ACE_SOCK_ACCEPTOR> acceptor(PORT);
  Handshake saludador(&db);
  saludador.saludar();
}
Exemple #25
0
int main()
{
    char* ip ="127.0.0.1";
    int port = 9999;

    Acceptor acceptor(ip, port, 3);

    acceptor.start();

}
Exemple #26
0
    std::vector<shortcut> simplify_monotone_line(const poly_line& l, const std::vector<point>& points) const
    {
        tangent_splitter splitter(l);
        point_distributor distributor(l, points);
        shortcut_acceptor acceptor(l);

        std::vector<shortcut> all_shortcuts;

        // note: no edges after last coordinate
        for (auto i = 0u; i < l.coordinates.size() - 1; ++i)
        {
            auto tangents = splitter(i);
            auto assignments = distributor(i, tangents);
            auto partial_shortcuts = acceptor(i, tangents, assignments);
            all_shortcuts.insert(all_shortcuts.end(), partial_shortcuts.begin(), partial_shortcuts.end());
        }

        return all_shortcuts;
    }
TEST_F(HandshakeTest, TxOK) {
  class Contestador_OK : public Contestador {
    public: const char* get_msg(){ return MSG_2; }
  };

  ACE_Acceptor<Contestador_OK, ACE_SOCK_ACCEPTOR> acceptor(PORT);

  MockDb db;
  Handshake saludador(&db);
  saludador.saludar();
}
int main()
{
	Poco::Net::ServerSocket serverSocket(PORT);
	Poco::Net::SocketReactor reactor;	
	Poco::Net::SocketAcceptor<Session> acceptor(serverSocket, reactor);

	std::cout << "Reactor: " << "starting..." << std::endl;
	reactor.run();
	
	return 0;
}
Exemple #29
0
int main(int argc, char* argv[])
{
	ACE_INET_Addr addr(1358);
	MyAcceptor acceptor(addr, ACE_Reactor::instance());

	while(true)
	{
		ACE_Reactor::instance()->handle_events();
	}
	return 0;
}
	void test_acceptor()
	{
		printf("main(): pid = %d, tid = %d\n", getpid(), this_thread::get_id().value());
		InetAddress listenAddr(8888);
		EventLoop loop;

		TcpAcceptor acceptor(&loop, listenAddr);
		acceptor.setNewConnectionCallback(newConnection);
		acceptor.listen();

		loop.loop();	
	}