CWebChannelServer::CWebChannelServer(const QHostAddress &anAddress, quint16 nPort, QObject *pParent)
	:	QObject(pParent),
		m_server("King James Pure Bible Search WebChannel Server", QWebSocketServer::NonSecureMode),
		m_clientWrapper(&m_server),
		m_HostAddress(anAddress),
		m_nHostPort(nPort)
{
	m_pGeoLocater = new CWebChannelGeoLocate(this);
	connect(m_pGeoLocater, SIGNAL(locationInfo(const CWebChannelClient *, const QString &, const QString &)), this, SLOT(setClientLocation(const CWebChannelClient *, const QString &, const QString &)));

	// setup the QWebSocketServer
	m_server.listen(anAddress, nPort);

	// create the CWebChannelAdminObjects
	m_pWebChannelAdminObjects = new CWebChannelAdminObjects(this);
	connect(m_pWebChannelAdminObjects.data(), SIGNAL(broadcast(const QString &)), this, SLOT(sendBroadcast(const QString &)));

	// Handle connections:
	connect(&m_clientWrapper, SIGNAL(clientConnected(WebSocketTransport*)), this, SLOT(en_clientConnected(WebSocketTransport*)));

#ifdef IS_CONSOLE_APP
	if (m_server.isListening()) {
		std::cout << QString("%1 UTC : KJPBS-WebChannel (pid=%2) started on interface \"%3\" port %4\n")
							.arg(QDateTime::currentDateTimeUtc().toString(Qt::ISODate))
							.arg(QCoreApplication::applicationPid())
							.arg(serverAddress().toString())
							.arg(serverPort())
							.toUtf8().data();
		std::cout.flush();
	}
#endif
}
Beispiel #2
0
int main(int argc, char** argv)
{
    sWorkingThread = new SWorkingThread();
    sCommunicationThread = new SCommunicationThread();
    sOutputThread = new SOutputThread();
    //sResourceThread = new SResourceThread();
    sOutputThread->run();
    sWorkingThread->run();
    sCommunicationThread->run();
    //sResourceThread->run();
    SNetAddress serverAddress((const char*)NULL, SUtil::Host2NetInt16(10000));
    SSocketServer ss(STREAM, serverAddress);
    if(ss.getError() != S_NO_ERROR)
    {
        SLog::msg("#### server init error : %d ####\n", ss.getError());
        return -1;
    }
    while(true)
    {
        SClientProp cp = ss.accept();
        SLog::msg("## new client ##\n");
        if(ss.getError() != S_NO_ERROR)
        {
            SLog::msg("## accept error ###\n");
            continue;
        }
        SEvent* e = new SCreateClientEvent(cp.address, cp.socket);
        SWorkingThreadManager::getInstance()->postEvent(NULL, e, SPostEvent::HIGH_PRIORITY);
    }

}
Beispiel #3
0
void HttpSocket::handleNewConnection()
{
    DBUG;
    while (hasPendingConnections()) {
        QTcpSocket *socket = nextPendingConnection();

        // prevent clients from sending too much data
        socket->setReadBufferSize(constMaxBuffer);

        static const QLatin1String constIpV6Prefix("::ffff:");

        QString peer=socket->peerAddress().toString();
        QString ifaceAddress=serverAddress().toString();
        const bool hostOk=peer==ifaceAddress || peer==mpdAddr || peer==(constIpV6Prefix+mpdAddr) ||
                          peer==QLatin1String("127.0.0.1") || peer==(constIpV6Prefix+QLatin1String("127.0.0.1"));

        DBUG << "peer:" << peer << "mpd:" << mpdAddr << "iface:" << ifaceAddress << "ok:" << hostOk;
        if (!hostOk) {
            sendErrorResponse(socket, 400);
            socket->close();
            DBUG << "Not from valid host";
            return;
        }

        connect(socket, SIGNAL(readyRead()), this, SLOT(readClient()));
        connect(socket, SIGNAL(disconnected()), this, SLOT(discardClient()));
    }
}
Beispiel #4
0
const std::string Settings::dump() const
{
    std::stringstream ss;
    ss << "Settings: " << std::endl;
    ss << "\tusername: "******"\t address: " << serverAddress() << std::endl;
    ss << "\t server?: " << (isServer() ? "true":"false") << std::endl;
    ss << "\t    port: " << port() << std::endl;

    return ss.str();
}
Beispiel #5
0
QString KDSoapServer::endPoint() const {
    const QHostAddress address = serverAddress();
    if (address == QHostAddress::Null)
        return QString();
    const QString addressStr = address == QHostAddress::Any ? QString::fromLatin1("127.0.0.1") : address.toString();
    return QString::fromLatin1("%1://%2:%3%4")
            .arg(QString::fromLatin1((d->m_features & Ssl)?"https":"http"))
            .arg(addressStr)
            .arg(serverPort())
            .arg(d->m_path);
}
void MoralityServer::StartServer(int myport)
{
    if (this->listen(QHostAddress::Any, myport))
    {
        qDebug() << "Server Started... at " << serverAddress() << " and port: " << this->serverPort();
    }
    else
    {
        qDebug() << "Server did NOT start...";
    }
}
void Manager::reportStatus()
{
    if(tcpServer->isListening()) {
        Q_EMIT statusChanged(tr("The server is running on\n\nIP: %1\nport: %2\n\n"
                                "%3 clients connected.")
                             .arg(serverAddress())
                             .arg(tcpServer->serverPort()).arg(clientsConnected));
    } else {
        Q_EMIT statusChanged(tr("Server not running."));
    }
}
static QString maliitServerAddress()
{
    org::maliit::Server::Address serverAddress(QStringLiteral("org.maliit.server"), QStringLiteral("/org/maliit/server/address"), QDBusConnection::sessionBus());

    QString address(serverAddress.address());

    // Fallback to old socket when org.maliit.server service is not available
    if (address.isEmpty())
        return QStringLiteral("unix:path=/tmp/meego-im-uiserver/imserver_dbus");

    return address;
}
Beispiel #9
0
void KDSoapServer::suspend()
{
    d->m_portBeforeSuspend = serverPort();
    d->m_addressBeforeSuspend = serverAddress();
    close();

    // Disconnect connected sockets, otherwise they could still make calls
    if (d->m_threadPool) {
        d->m_threadPool->disconnectSockets(this);
    } else if (d->m_mainThreadSocketList) {
        d->m_mainThreadSocketList->disconnectAll();
    }
}
Beispiel #10
0
Client::Client()
{
	GameObjectRegistry::sInstance->RegisterCreationFunction( 'SHIP', ShipClient::StaticCreate );
	GameObjectRegistry::sInstance->RegisterCreationFunction( 'COIN', TommyCoinClient::StaticCreate );

	wstring destination = StringUtils::GetCommandLineArg( 1 );
	wstring name = StringUtils::GetCommandLineArg( 2 );

	SocketAddress serverAddress( destination );

	NetworkManagerClient::StaticInit( serverAddress, name );

	NetworkManagerClient::sInstance->SetDropPacketChance( 0.6f );
}
Beispiel #11
0
void GameScene::runLogic(float deltaTime, Game& game) {
    if(game.server) {

        // SERVER

        cooldown -= deltaTime;
        enemySpawnCooldown -= deltaTime;
        enemyCooldown -= deltaTime;
        difficulty += deltaTime * 30.0f;

        bgMotion += deltaTime * bgSpeed;
        if(bgMotion > 256.0f)
            bgMotion -= 256.0f;
        bgSprite->setPosition(0.0f, -600.0f + bgMotion);

        shooting(deltaTime, game);
        spawningEnemies(deltaTime, game);
        flyEnemyPlasma(deltaTime, game);

        player.runLogic(deltaTime, game);

        std::string scoreString = std::to_string(score);
        scoreText.setString("Score: " + scoreString);
        scoreText.setFont(*game.font);
        escText.setFont(*game.font);

        std::string scoreString2 = std::to_string(score2);
        scoreText2.setString("Score: " + scoreString2);
        scoreText2.setFont(*game.font);

        sf::Packet packet;
        packet << player.position.x << player.position.y;
        sf::IpAddress clientAddress(game.clientAddress);
        game.socket->send(packet, clientAddress, game.udpPortClient);

    } else {

        // CLIENT

        sf::Packet packet;
        float x, y;
        sf::IpAddress serverAddress(game.serverAddress);
        game.socket->receive(packet, serverAddress, game.udpPortClient);
        if(packet >> x >> y) {
            player.position.x = x;
            player.position.y = y;
        }
    }
}
Beispiel #12
0
   void Server::start()
   {
      listen();

      cout << "Starting server..." << endl;

      cout << "note: server will shutdown automatically after an inactivity period of " << INACTIVITY_TIMEOUT / 1000 << " seconds" << endl;
      //cout << " -> active threads: " << threadpool_->activeThreadCount() << endl;

      cout << endl;

      cout << "Server starting to listen on address " << serverAddress().toString().toStdString();
      cout << " and port " << serverPort() << endl;

      inactivity_timer_.start( INACTIVITY_TIMEOUT );
   }
Beispiel #13
0
bool RpcServer::registerService(::google::protobuf::Service *service,
    QHostAddress address, quint16 tcpPortNum)
{
    this->service = service;

    if (!listen(address, tcpPortNum))
    {
        qDebug("Unable to start the server on <%s>: %s",
                qPrintable(address.toString()),
                errorString().toAscii().constData());
        return false;
    }

    qDebug("The server is running on %s: %d", 
            serverAddress().toString().toAscii().constData(),
            serverPort());
    return true;
}
Beispiel #14
0
/****************************************************************
*   Purpose:  Starts the server, and notifies user that it is
*             listening for connections.
*
*     Entry:  Called after an instances of a CG_Server object is
*             created.
*
*      Exit:  Starts the server.
****************************************************************/
void CG_Server::StartServer()
{
    // Possibly use QHostAddress add("192.168.1.100"); in the future

    // Tell server to listen to incoming connections on the following port

    QHostAddress add("192.168.0.118");
    if(!this->listen(QHostAddress(add), 9556))
    {
        // Could not set listener on localhost, so echo could not start server
        qDebug() << "Could not start server";
    }
    else
    {
        // Listener has been set on localhost, which means the server started
        qDebug() << "Chessgames server started!";
        qDebug() << "Listening on: " <<  serverAddress().toString() << " ...\r\n";
    }
}
Beispiel #15
0
bool LoginWidget::checkServerAddress(){

    QString serverHostAddress = serverAddress();
    if(serverHostAddress.isEmpty()){
        QMessageBox::critical(this, tr("Error"), tr("Server Address Required!"));
        localServer->close();
        if(ui.groupBoxConfiguration->isHidden()){
            ui.toolButtonConfig->setChecked(true);
            ui.groupBoxConfiguration->setVisible(true);
        }
        if(!ui.comboBoxServerIP->count()){
            ui.toolButtonServersManager->click();
        }  
        return false;
    }
    
    return true;
    
}
Beispiel #16
0
void LoginWidget::verifyUser(){

    if(canLogin()){
        QString serverHostAddress = serverAddress();
        //        if(serverHostAddress.isEmpty()){
        //            QMessageBox::critical(this, tr("Error"), tr("Server Address Required!"));
        //            localServer->close();
        //            ui.toolButtonConfig->click();
        //            if(!ui.comboBoxServerIP->count()){
        //                ui.toolButtonServersManager->click();
        //            }
        //            return;
        //        }

        switchUI(VERIFYING);
        emit signalRequestLogin(QHostAddress(serverHostAddress), serverPort());
        
        //QTimer::singleShot(30000, this, SLOT(loginTimeout()));
    }


    //	Login login(user,this);
    //	if(canLogin() && login.isVerified()){
    //		//发射验证成功的消息
    //		emit signalUserVerified();

    //		qDebug()<<"----LoginWidget::verifyUser()~~User Verified!";

    //		return true;
    //	}else{
    //		user->setUserID("");
    //		user->setPassword("");
    //		user->setVerified(false);
    //		localServer->close();
    //		switchUI(NORMAL);
    //		qDebug()<<"XXXXLoginWidget::verifyUser()~~User Verify Failed!";
    //	}

    //	return false;

}
Beispiel #17
0
static void initializeInspectorServer()
{
#if ENABLE(INSPECTOR_SERVER)
    static bool initialized = false;
    if (initialized)
        return;

    // It should be set to true always.
    // Because it is to ensure initializeInspectorServer() is executed only once,
    // even if the server fails to run.
    initialized = true;

    String serverAddress(getenv("WEBKIT_INSPECTOR_SERVER"));
    if (!serverAddress.isNull()) {
        String bindAddress = ASCIILiteral("127.0.0.1");
        unsigned short port = 2999;

        Vector<String> result;
        serverAddress.split(':', result);

        if (result.size() == 2) {
            bindAddress = result[0];
            bool ok = false;
            port = result[1].toUInt(&ok);
            if (!ok) {
                port = 2999;
                LOG_ERROR("Couldn't parse the port. Using 2999 instead.");
            }
        } else
            LOG_ERROR("Couldn't parse %s, wrong format? Using 127.0.0.1:2999 instead.", serverAddress.utf8().data());

        if (!WebInspectorServer::shared().listen(bindAddress, port))
            LOG_ERROR("Couldn't start listening on: IP address=%s, port=%d.", bindAddress.utf8().data(), port);

        return;
    }

    LOG(InspectorServer, "To start inspector server set WEBKIT_INSPECTOR_SERVER to 127.0.0.1:2999 for example.");
#endif
}
Beispiel #18
0
int main(int argc, char** argv)
{
    Poco::Net::SocketAddress serverAddress("127.0.0.1:36911");
    GameMessageHandler handler;

    const int client_count = 100;
    g_tcpClient = new TcpClient(handler);

    try
    {
        std::cout << "starting.." << std::endl;
        for (int i = 0; i < 1; i++)
        {
            g_tcpClient->connect(serverAddress);

            Protocol::CSRegisterReq registerRequest;
            registerRequest.username = "******";
            registerRequest.password = "******";
            g_tcpClient->sendMessage(Opcodes::CSRegisterReq, registerRequest);

            Protocol::CSLoginReq loginRequest;
            loginRequest.account = "*****@*****.**";
            loginRequest.password = "******";
            g_tcpClient->sendMessage(Opcodes::CSLoginReq, loginRequest);
        }

        std::cout << "finished." << std::endl;
    }
    catch (const Poco::Exception& e)
    {
        std::cout << e.displayText() << std::endl;
    }

    getchar();

    delete g_tcpClient;
    return 0;
}
Beispiel #19
0
static void initInspectorServer()
{
#if ENABLE(INSPECTOR_SERVER)
    static bool initialized = false;
    if (initialized)
        return;

    initialized = true;
    String serverAddress(g_getenv("WEBKIT_INSPECTOR_SERVER"));

    if (!serverAddress.isNull()) {
        String bindAddress = "127.0.0.1";
        unsigned short port = 2999;

        Vector<String> result;
        serverAddress.split(":", result);

        if (result.size() == 2) {
            bindAddress = result[0];
            bool ok = false;
            port = result[1].toInt(&ok);
            if (!ok) {
                port = 2999;
                LOG_ERROR("Couldn't parse the port. Use 2999 instead.");
            }
        } else
            LOG_ERROR("Couldn't parse %s, wrong format? Use 127.0.0.1:2999 instead.", serverAddress.utf8().data());

        if (!WebInspectorServer::shared().listen(bindAddress, port))
            LOG_ERROR("Couldn't start listening on: IP address=%s, port=%d.", bindAddress.utf8().data(), port);
        return;
    }

    LOG(InspectorServer, "To start inspector server set WEBKIT_INSPECTOR_SERVER to 127.0.0.1:2999 for example.");
#endif
}
Beispiel #20
0
//loop through command line arguments and extract settings
void Settings::parse(const int argc, const char** argv)
{
    bool hasUserName = false;   //assume user hasn't entered a username

    //loops through arguments, reads in each argument and decides what to do with it
    for(int ii = 0; ii < argc; ++ii)
    {
        std::string arg(argv[ii]);

        if (arg[0] != '-')
        {
            continue;   //not a switch, skip it
        }

        if(arg.find("-username="******"-address=") == 0)    //are we setting a server IP?
        {
            std::string address(getArgValue(arg));
            try
            {
                (void)serverAddress(address);    //set and validate requested server address
            }
            catch (BeeChatException bce)
            {
                throw;    //rethrow the same exception
            }
        }

        else if(arg.find("-server") == 0)
        {
            (void)isServer(true);    //request to bee a server
        }

        else if(arg.find("-port=") == 0)
        {
            std::string portStr(getArgValue(arg));
            try
            {
                (void)port((unsigned short)atoi(portStr.c_str()));    //set and validate requested port
            }
            catch(BeeChatException e)
            {
                std::stringstream ss;
                ss << "Could not set port: " << e.type() << ":" << e.message();
                throw BeeChatException(eET_invalid_port, ss.str());
            }
        }

        else
        {
            std::stringstream ss;
            ss << "Unknown argument: " << arg;
            throw BeeChatException(eET_unknown_arg, ss.str());
        }
    }

    if(!hasUserName)
    {
        throw BeeChatException(eET_empty_username, "No username supplied");
    }

}
Beispiel #21
0
int main(int argc, char ** argv)
{
	int status = EXIT_FAILURE;

	try
	{
		avatar::AppEnvironment env(argc, argv);
		avatar::cmdline_utils::Parser cmdlineParser;
		std::unique_ptr<avatar::RiftApp> app;

		auto cmdlineParserResult = cmdlineParser.parseOptions();

		switch (cmdlineParserResult.first)
		{

			case avatar::cmdline_utils::Parser::Status::LaunchColorCubeDemo:
			{
				std::wcout << L"Info >> description: launching color cube demo" << std::endl;
				app.reset(new avatar::ColorCubeApp);
			}
			break;

			case avatar::cmdline_utils::Parser::Status::LaunchTextureCubeDemo:
			{
				std::wcout << L"Info >> description: launching texture cube demo" << std::endl;
				app.reset(new avatar::TexCubeApp);
			}
			break;

			case avatar::cmdline_utils::Parser::Status::LaunchMonoWebcamDemo:
			{
				std::wcout << L"Info >> description: launching mono webcam demo" << std::endl;
				app.reset(new avatar::WebcamMonoApp);
			}
			break;

			case avatar::cmdline_utils::Parser::Status::LaunchStereoWebcamDemo:
			{
				std::wcout << L"Info >> description: launching stereo webcam demo" << std::endl;
				app.reset(new avatar::WebcamStereoApp);
			}
			break;

			case avatar::cmdline_utils::Parser::Status::LaunchClientDemo:
			{
				QString const serverAddressString = cmdlineParser.value(avatar::cmdline_utils::launchClientDemo);
				QHostAddress serverAddress(serverAddressString);

				std::wcout << L"Info >> description: launching client demo with server IP address " << serverAddressString.toStdWString() << std::endl;

				app.reset(new avatar::VideoStreamClientApp(serverAddress));
			}
			break;

			case avatar::cmdline_utils::Parser::Status::LaunchServerDemo:
			{
				std::wcout << L"Info >> description: launching server demo" << std::endl;
				app.reset(new avatar::VideoStreamServerApp);
			}
			break;

			case avatar::cmdline_utils::Parser::Status::LaunchFirstPersonViewDemo:
			{
				std::wcout << L"Info >> description: launching FPV demo" << std::endl;


				//
				// Find arduino serial port.
				//

				QList<QSerialPortInfo> const ports = QSerialPortInfo::availablePorts();
				QList<QSerialPortInfo>::const_iterator arduinoPort = ports.cend();

				for (auto it = ports.cbegin(); it != ports.cend(); ++it)
				{
					QString const description = it->description();

					if (description.contains("arduino", Qt::CaseInsensitive))
					{
						arduinoPort = it;
						break;
					}
				}

				if (arduinoPort == ports.cend())
				{
					std::wcout << L"Error >> description: failed to find arduino serial port" << std::endl;
					return EXIT_FAILURE;
				}


				//
				// Find a webcam.
				//

				auto const cameras = QCameraInfo::availableCameras();

				if (cameras.empty())
				{
					std::wcout << L"Error >> description: failed to find webcam devices" << std::endl;
					return EXIT_FAILURE;
				}


				//
				// Setup both the interpreter for the arduino port and the camera.
				//
				
				auto commandInterpreter = avatar::FirstPersonViewSerialCli::create(*arduinoPort, QSerialPort::Baud115200, QByteArray("Servo>"), 50);
				auto imageSystem = avatar::ImageSystem::create(std::make_unique<avatar::WebcamImageReader>(cameras[0]), std::make_unique<avatar::WebcamImageProcessor>());

				app.reset(new avatar::FirstPersonViewApp(std::move(commandInterpreter), std::move(imageSystem)));
			}
			break;

			case avatar::cmdline_utils::Parser::Status::ShowHelp:
			{
				cmdlineParser.showHelp(EXIT_SUCCESS); // showHelp() will exit the application
			}
			break;

			case avatar::cmdline_utils::Parser::Status::Error:
			{
				std::wcout << cmdlineParserResult.second.toStdWString() << std::endl;
				cmdlineParser.showHelp(EXIT_FAILURE); // showHelp() will exit the application
			}
			break;

			default:
			{
				Q_ASSERT(false);
				cmdlineParser.showHelp(EXIT_FAILURE); // showHelp() will exit the application
			}

		}

		app->show();
		status = env.exec();

	}
	catch (avatar::Exception const & e)
	{
		std::wcout << e.what().toStdWString() << std::endl;
	}

	return status;
}
Beispiel #22
0
bool MyApp::OnInit()
{
	gAppHandler = this;

	wxString sFullModleName = ::wxGetFullModuleName();
	wxString sAppName = this->GetAppName();
	size_t nFind = sFullModleName.rfind(sAppName);
	gAppPath = sFullModleName.substr(0, nFind-1).c_str();

	setAutorun(BIWOO_NAME.c_str(), sFullModleName.c_str());

	wxString xmlFile(gAppPath);
	xmlFile.Append(wxT("/default/setting.xml"));
	gSetting.load(xmlFile.c_str());

	setlocale(LC_ALL, gSetting.locale().c_str());
	//setlocale(LC_ALL,"Chinese-simplified");
	//std::locale::global(std::locale("Chinese-simplified"));
	
	CCgcAddress serverAddress(gSetting.address(), CCgcAddress::ST_UDP);
	if (!m_biwoo.start(serverAddress, (CbiwooHandler*)this))
	{
		//m_biwoo.stop();
		//return false;
	}

	xmlFile = gAppPath.c_str();
	xmlFile.Append(wxT("/default/"));
	xmlFile.Append(gSetting.langtext());
	gLangText.load(xmlFile.c_str());

	/////////////////////////////////////
	// test
	//CDlgSetting dlgSetting(NULL);
	//dlgSetting.ShowModal();

    if ( !wxApp::OnInit() )
	{
		m_biwoo.stop();
        return false;
	}

	CDlglogin dlgLogin(NULL, false);
	int ret = dlgLogin.ShowModal();
	if (ret != wxID_OK)
	{
		m_biwoo.stop();
		wxApp::OnExit();
		return false;
	}
	gMyAccount = dlgLogin.accountInfo();
	BOOST_ASSERT (gMyAccount.get() != 0);

    // create the main application window
    MyFrame * frame = new MyFrame(_T("BIWOO App"), wxSize(700, 450));
	m_biwoo.setHandler(gAppHandler);
	m_biwoo.accountLoad();

	wxString title = wxString::Format("%s - %s(%s)", BIWOO_NAME.c_str(), gMyAccount->getUserinfo()->getUserName().c_str(), gMyAccount->getUserinfo()->getAccount().c_str());
	frame->SetTitle(title);
	frame->setTaskBarIcon(wxT("mainframe.ico"), title);

#if defined(__WXMOTIF__)
    int width, height;
    frame->GetSize(& width, & height);
    frame->SetSize(wxDefaultCoord, wxDefaultCoord, width, height);
#endif

    // and show it (the frames, unlike simple controls, are not shown when
    // created initially)
	frame->SetMinSize(wxSize(700, 450));
    frame->Show(true);

    //SetTopWindow(frame);

    // success: wxApp::OnRun() will be called which will enter the main message
    // loop and the application will run. If we returned false here, the
    // application would exit immediately.
    return true;
}
int main(int argc, char **argv)
{
    ESFUInt16 multiplexerCount = 4;
    const char *dottedIp = "127.0.0.1";
    ESFUInt16 port = 8080;
    ESFInt16 sockets = 1;
    bool reuseConnections = false;
    int logLevel = ESFLogger::Notice;

    {
        int result = 0;

        while (true)
        {
            result = getopt(argc, argv, "l:m:a:p:s:r");

            if (0 > result)
            {
                break;
            }

            switch (result)
            {
                case 'l':

                    /*
                    None = 0,
                    Emergency = 1,   System-wide non-recoverable error.
                    Alert = 2,       System-wide non-recoverable error imminent.
                    Critical = 3,    System-wide potentially recoverable error.
                    Error = 4,       Localized non-recoverable error.
                    Warning = 5,     Localized potentially recoverable error.
                    Notice = 6,      Important non-error event.
                    Info = 7,        Non-error event.
                    Debug = 8        Debugging event.
                    */

                    logLevel = atoi(optarg);
                    break;

                case 'm':

                    multiplexerCount = atoi(optarg);
                    break;

                case 'a':

                    dottedIp = optarg;
                    break;

                case 'p':

                    port = atoi(optarg);
                    break;

                case 's':

                    sockets = atoi(optarg);
                    break;

                case 'r':

                    reuseConnections = true;
                    break;

                default:

                    printHelp();

                    return 2;
            }
        }
    }

    ESFConsoleLogger::Initialize((ESFLogger::Severity) logLevel);
    ESFLogger *logger = ESFConsoleLogger::Instance();

    if (logger->isLoggable(ESFLogger::Notice))
    {
        logger->log(ESFLogger::Notice, __FILE__, __LINE__,
                    "[main] starting. logLevel: %d, threads: %d, server: %s, port: %d, sockets: %d, reuseConnections: %s",
                    logLevel, multiplexerCount, dottedIp, port, sockets,  reuseConnections ? "true" : "false");
    }

    AWSClientSocket::SetReuseConnections(reuseConnections);
    ESFSocketAddress serverAddress( dottedIp, port, ESFSocketAddress::TCP );

    //
    // Install signal handlers
    //

    signal(SIGHUP, SIG_IGN);
    signal(SIGPIPE, SIG_IGN);
    signal(SIGINT, AWSRawEchoClientSignalHandler);
    signal(SIGQUIT, AWSRawEchoClientSignalHandler);
    signal(SIGTERM, AWSRawEchoClientSignalHandler);



    ESFDiscardAllocator discardAllocator(4000, ESFSystemAllocator::GetInstance());
    ESFSharedAllocator rootAllocator(&discardAllocator);
    ESFAllocatorCleanupHandler rootAllocatorCleanupHandler(&rootAllocator);

    ESFError error = rootAllocator.initialize();

    if (ESF_SUCCESS != error)
    {
        if (logger->isLoggable(ESFLogger::Critical))
        {
            char buffer[100];

            ESFDescribeError(error, buffer, sizeof(buffer));

            logger->log(ESFLogger::Critical, __FILE__, __LINE__,
                        "[main] Cannot initialize root allocator: %s", buffer);
        }

        return error;
    }

    ESFEpollMultiplexerFactory epollFactory("EpollMultiplexer",
                                            logger,
                                            &rootAllocator);

    ESFUInt16 maxSockets = ESFSocketMultiplexerDispatcher::GetMaximumSockets();

    if (sockets > maxSockets)
    {
        if (logger->isLoggable(ESFLogger::Critical))
        {
            logger->log(ESFLogger::Critical, __FILE__, __LINE__,
                        "Raise ulimit -n, only %d sockets can be created\n", maxSockets);
        }

        return 1;
    }

    if (logger->isLoggable(ESFLogger::Notice))
    {
        logger->log(ESFLogger::Notice, __FILE__, __LINE__,
                    "[main] Maximum sockets %d", maxSockets);
    }

    ESFSocketMultiplexerDispatcher dispatcher(maxSockets,
                                              multiplexerCount,
                                              &epollFactory,
                                              &rootAllocator,
                                              "EpollDispatcher",
                                              logger);


    error = dispatcher.start();

    if (ESF_SUCCESS != error)
    {
        if (logger->isLoggable(ESFLogger::Critical))
        {
            char buffer[100];

            ESFDescribeError(error, buffer, sizeof(buffer));

            logger->log(ESFLogger::Critical, __FILE__, __LINE__,
                        "[main] Cannot start multiplexer dispatcher: %s", buffer);
        }

        return error;
    }

    AWSClientSocketFactory factory(maxSockets,
                                   &SuccessCounter,
                                   &dispatcher,
                                   logger);

    sleep(1);   // give the worker threads a chance to start - cleans up perf testing numbers a bit

    struct timeval startTime;
    AWSPerformanceCounter::GetTime(&startTime);

    for (int i = 0; i < sockets; ++i)
    {
        error = factory.addNewConnection(serverAddress);

        if (ESF_SUCCESS != error)
        {
            if (logger->isLoggable(ESFLogger::Critical))
            {
                char buffer[100];

                ESFDescribeError(error, buffer, sizeof(buffer));

                logger->log(ESFLogger::Critical, __FILE__, __LINE__,
                            "[main] Cannot add new connection: %s", buffer);
            }

            return error;
        }
    }

    if (logger->isLoggable(ESFLogger::Notice))
    {
        logger->log(ESFLogger::Notice, __FILE__, __LINE__, "[main] started");
    }

    while (IsRunning)
    {
        sleep(60);
    }

    if (logger->isLoggable(ESFLogger::Notice))
    {
        logger->log(ESFLogger::Notice, __FILE__, __LINE__, "[main] stopping");
    }

    dispatcher.stop();

    if (logger->isLoggable(ESFLogger::Notice))
    {
        logger->log(ESFLogger::Notice, __FILE__, __LINE__, "[main] stopped");
    }

    ESFConsoleLogger::Destroy();

    ESFUInt32 seconds = StopTime.tv_sec - startTime.tv_sec;
    ESFUInt32 microseconds = 0;

    if (StopTime.tv_usec < startTime.tv_usec)
    {
        --seconds;
        microseconds = StopTime.tv_usec - (ESF_UINT32_C(1000000) - startTime.tv_usec);
    }
    else
    {
        microseconds = StopTime.tv_usec - startTime.tv_usec;
    }

    SuccessCounter.printSummary();
    fprintf(stdout, "\tTotal Sec: %u.%u\n", seconds, microseconds);

    return ESF_SUCCESS;
}
Beispiel #24
0
void LoginWidget::updateUserLoginServerInfo(){
    qDebug()<<"--LoginWidget::updateUserLoginServerInfo() serverAddress:"<<serverAddress();

    user->setLoginServerAddress(serverAddress());
    user->setLoginServerPort(serverPort());
}
Beispiel #25
0
int main(int argc, char** argv) {
    if (argc != 3 && argc != 5 && argc != 6) {
        cout << VERSION << endl;
        cout << "USAGE FOR STANDALONE: qsspn qsspn_file ctrl_file" << endl;
        cout << "USAGE FOR SERVER: qsspn qsspn_file ctrl_file address port cache_size" << endl;
        cout << "USAGE FOR CLIENT: qsspn qsspn_file ctrl_file address port" << endl;
        cout << "The qsspn_file file with extension .json is read as Json file" << endl;
        cout << "The qsspn file without .json extension is assumed to be in old qsspn format" << endl;
        cout << "Example cache size is 100000000" << endl;
        exit(1);
    }

    if (argc == 3) {//standalone
        PetriNet *pn = new PetriNet();
        string path(argv[1]);
        string path1(argv[2]);
        if (isJason(path)) {
            pn->readModel(path);
        } else {
            pn->readPetriNet(path);
        }
        pn->runWorkflowStandalone(path1);
        exit(0);
    } else if (argc == 5) {//client
        PetriNet *pn = new PetriNet();
        string path(argv[1]);
        string path1(argv[2]);
        string serverAddress(argv[3]);
        string serverPort(argv[4]);
        if (isJason(path)) {
            pn->readModel(path);
        } else {
            pn->readPetriNet(path);
        }
       pn->runWorkflowClient(path1, serverAddress, serverPort);
        exit(0);
    } else try {//server
        string path(argv[1]);
        string path1(argv[2]);
        string address(argv[3]);
        string port(argv[4]);
        int cache_size = atoi(argv[5]);

        Cache *cache = new Cache(cache_size);
        PetriNet *pn = new PetriNet();
        if (isJason(path)) {
            pn->readModel(path);
        } else {
            pn->readPetriNet(path);
        }

        fstream infile;
        string word;
        vector<string> text;

        infile.open(path1.c_str());
        if (!infile) {
            cerr << "Could not open file:" << path1 << endl;
            exit(0);
        }

        while (infile >> word) text.push_back(word);
        infile.close();

        asio::io_service io_service;

        MetabolismServer server(address, port, io_service, 1, pn, cache, text);

        server.run();

        delete pn;
        delete cache;
    } catch (std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
        return 1;
    }
    return 0;
}
Beispiel #26
0
void HttpSocket::readClient()
{
    if (terminated) {
        return;
    }

    QTcpSocket *socket = static_cast<QTcpSocket *>(sender());
    if (socket->canReadLine()) {
        QList<QByteArray> tokens = split(socket->readLine()); // QRegExp("[ \r\n][ \r\n]*"));
        if (tokens.length()>=2 && "GET"==tokens[0]) {
            QStringList params = QString(socket->readAll()).split(QRegExp("[\r\n][\r\n]*"));

            DBUG << "params" << params << "tokens" << tokens;
            if (!isFromMpd(params)) {
                sendErrorResponse(socket, 400);
                socket->close();
                DBUG << "Not from MPD";
                return;
            }

            QString peer=socket->peerAddress().toString();
            QString ifaceAddress=serverAddress().toString();
            bool hostOk=peer==ifaceAddress || peer==mpdAddr || peer==QLatin1String("127.0.0.1");

            DBUG << "peer:" << peer << "mpd:" << mpdAddr << "iface:" << ifaceAddress << "ok:" << hostOk;
            if (!hostOk) {
                sendErrorResponse(socket, 400);
                socket->close();
                DBUG << "Not from valid host";
                return;
            }

            QUrl url(QUrl::fromEncoded(tokens[1]));
            #if QT_VERSION < 0x050000
            QUrl &q=url;
            #else
            QUrlQuery q(url);
            #endif
            bool ok=false;
            qint32 readBytesFrom=0;
            qint32 readBytesTo=0;
            getRange(params, readBytesFrom, readBytesTo);

            DBUG << "readBytesFrom" << readBytesFrom << "readBytesTo" << readBytesTo;
            if (q.hasQueryItem("cantata")) {
                Song song=HttpServer::self()->decodeUrl(url);

                if (!isCantataStream(song.file)) {
                    sendErrorResponse(socket, 400);
                    socket->close();
                    DBUG << "Not cantata stream file";
                    return;
                }

                if (song.isCdda()) {
                    #if defined CDDB_FOUND || defined MUSICBRAINZ5_FOUND
                    QStringList parts=song.file.split("/", QString::SkipEmptyParts);
                    if (parts.length()>=3) {
                        QString dev=QLatin1Char('/')+parts.at(1)+QLatin1Char('/')+parts.at(2);
                        CdParanoia cdparanoia(dev, false, false, true);

                        if (cdparanoia) {
                            int firstSector = cdparanoia.firstSectorOfTrack(song.id);
                            int lastSector = cdparanoia.lastSectorOfTrack(song.id);
                            qint32 totalSize = ((lastSector-firstSector)+1)*CD_FRAMESIZE_RAW;
                            int count = 0;
                            bool writeHeader=0==readBytesFrom; // Only write header if we are not seeking...
//                            int bytesToDiscard = 0; // Number of bytes to discard in first read sector due to range request in HTTP header
//                            if (readBytesFrom>=ExtractJob::constWavHeaderSize) {
//                                readBytesFrom-=ExtractJob::constWavHeaderSize;
//                            }

//                            if (readBytesFrom>0) {
//                                int sectorsToSeek=readBytesFrom/CD_FRAMESIZE_RAW;
//                                firstSector+=sectorsToSeek;
//                                bytesToDiscard=readBytesFrom-(sectorsToSeek*CD_FRAMESIZE_RAW);
//                            }
                            cdparanoia.seek(firstSector, SEEK_SET);
                            ok=true;
                            writeMimeType(QLatin1String("audio/x-wav"), socket, readBytesFrom, totalSize+ExtractJob::constWavHeaderSize, false);
                            if (writeHeader) {
                                ExtractJob::writeWavHeader(*socket, totalSize);
                            }
                            bool stop=false;
                            while (!terminated && (firstSector+count) <= lastSector && !stop) {
                                qint16 *buf = cdparanoia.read();
                                if (!buf) {
                                    break;
                                }
                                char *buffer=(char *)buf;
                                qint32 writePos=0;
                                qint32 toWrite=CD_FRAMESIZE_RAW;

//                                if (bytesToDiscard>0) {
//                                    int toSkip=qMin(toWrite, bytesToDiscard);
//                                    writePos=toSkip;
//                                    toWrite-=toSkip;
//                                    bytesToDiscard-=toSkip;
//                                }

                                if (toWrite>0 && !write(socket, &buffer[writePos], toWrite, stop)) {
                                    break;
                                }
                                count++;
                            }
                        }
                    }
                    #endif
                } else if (!song.file.isEmpty()) {
                    #ifdef Q_OS_WIN
                    if (tokens[1].startsWith("//") && !song.file.startsWith(QLatin1String("//")) && !QFile::exists(song.file)) {
                        QString share=QLatin1String("//")+url.host()+song.file;
                        if (QFile::exists(share)) {
                            song.file=share;
                            DBUG << "fixed share-path" << song.file;
                        }
                    }
                    #endif

                    QFile f(song.file);

                    if (f.open(QIODevice::ReadOnly)) {
                        qint32 totalBytes = f.size();

                        writeMimeType(detectMimeType(song.file), socket, readBytesFrom, totalBytes, true);
                        ok=true;
                        qint32 readPos = 0;
                        qint32 bytesRead = 0;

                        if (0!=readBytesFrom) {
                            if (!f.seek(readBytesFrom)) {
                                ok=false;
                            }
                            bytesRead+=readBytesFrom;
                        }

                        if (0!=readBytesTo && readBytesTo>readBytesFrom && readBytesTo!=totalBytes) {
                            totalBytes-=(totalBytes-readBytesTo);
                        }

                        if (ok) {
                            static const int constChunkSize=32768;
                            char buffer[constChunkSize];
                            bool stop=false;
                            do {
                                bytesRead = f.read(buffer, constChunkSize);
                                readPos+=bytesRead;
                                if (!write(socket, buffer, bytesRead, stop) || f.atEnd()) {
                                    break;
                                }
                            } while (readPos<totalBytes && !stop && !terminated);
                        }
                    } else {
                        DBUG << "Filed to open" << song.file;
                    }
                }
            }

            if (!ok) {
                sendErrorResponse(socket, 404);
            }

            socket->close();

            if (QTcpSocket::UnconnectedState==socket->state()) {
                delete socket;
            }
        }
    }
}
Beispiel #27
0
// Virtual functions
void NtpTest::Run( std::ostream & p_Trace )
{
	std::cout << "-------------------------------------------" << std::endl;
	std::cout << "Starting NTP test." << std::endl;

	// Open a ntp client
	Bit::Ntp ntp( 0, 123 );

	// Assert a ntp header
	Bit::Ntp::Header header1( Bit::Ntp::Header::NoWarning, 4, Bit::Ntp::Header::Client );
	TestAssert( header1.GetLeapIndicator( ) == Bit::Ntp::Header::NoWarning );
	TestAssert( header1.GetVersion( ) == 4 );
	TestAssert( header1.GetMode( ) == Bit::Ntp::Header::Client );

	// Assert the ntp set and get functions
	Bit::Ntp::Header header2;
	header2.SetLeapIndicator( Bit::Ntp::Header::Remove );
	header2.SetVersion( 5 );
	header2.SetMode( Bit::Ntp::Header::Server );
	TestAssert( header2.GetLeapIndicator( ) == Bit::Ntp::Header::Remove );
	TestAssert( header2.GetVersion( ) == 5 );
	TestAssert( header2.GetMode( ) == Bit::Ntp::Header::Server );

	// Send request to NTP server
	Bit::Address serverAddress( "0.europe.pool.ntp.org" );
	ntp.SendRequest( header1, serverAddress );
	std::cout << "Sent request." << std::endl;

	// Assert Receive response from NTP server
	Bit::Ntp::Header header3( Bit::Ntp::Header::NoWarning, 4, Bit::Ntp::Header::Client );
	TestAssert( ntp.ReceiveResponse( header3, serverAddress ) == true );
	std::cout << "Received response:" << std::endl;

	// Print the response
	std::cout << " Leap: "				<< (Bit::Uint32)header3.GetLeapIndicator( ) << std::endl;
	std::cout << " Version: "			<< (Bit::Uint32)header3.GetVersion( ) << std::endl;
	std::cout << " Mode: "				<< (Bit::Uint32)header3.GetMode( ) << std::endl;
	std::cout << " Stratum: "			<< (Bit::Uint32)header3.GetStratum( ) << std::endl;
	std::cout << " Polling interval: "	<< (Bit::Uint32)header3.GetPollInterval( ) << std::endl;
	std::cout << " Precision: "			<< (Bit::Uint32)header3.GetPrecision( ) << std::endl;
	std::cout << " Root delay: "		<< header3.GetRootDelay( ) << std::endl;
	std::cout << " Root dispersion: "	<< header3.GetRootDispersion( ) << std::endl;
	Bit::Address address( header3.GetReferenceClock( ) );
	std::cout << " Referense address: "	<< (int)address.GetA( ) << "."
								<< (int)address.GetB( ) << "."
								<< (int)address.GetC( ) << "."
								<< (int)address.GetD( ) << std::endl;
	std::cout << std::endl;
	std::cout	<< " Reference time       : " << header3.GetReferenceTimestamp( ).GetTimeString( )
				<< " ("	<< static_cast<Bit::Float64>( header3.GetReferenceTimestamp( ).GetFractions( ) ) / static_cast<Bit::Float64>( 0xFFFFFFFF ) <<  ")"  << std::endl;
	std::cout << " Reference local time : " << header3.GetTransmitTimestamp( ).GetLocalTimeString( )
				<< " ("	<< static_cast<Bit::Float64>( header3.GetReferenceTimestamp( ).GetFractions( ) ) / static_cast<Bit::Float64>( 0xFFFFFFFF ) <<  ")"  << std::endl;
	std::cout << std::endl;
	std::cout << " Origin time       : " << header3.GetOriginateTimestamp( ).GetTimeString( )
				<< " ("	<< static_cast<Bit::Float64>( header3.GetOriginateTimestamp( ).GetFractions( ) ) / static_cast<Bit::Float64>( 0xFFFFFFFF ) <<  ")"  << std::endl;
	std::cout << " Origin local time : " << header3.GetOriginateTimestamp( ).GetLocalTimeString( )
				<< " ("	<< static_cast<Bit::Float64>( header3.GetOriginateTimestamp( ).GetFractions( ) ) / static_cast<Bit::Float64>( 0xFFFFFFFF ) <<  ")"  << std::endl;
	std::cout << std::endl;
	std::cout << " Receive time       : " << header3.GetReceiveTimestamp( ).GetTimeString( )
				<< " ("	<< static_cast<Bit::Float64>( header3.GetReceiveTimestamp( ).GetFractions( ) ) / static_cast<Bit::Float64>( 0xFFFFFFFF ) <<  ")"  << std::endl;
	std::cout << " Receive local time : " << header3.GetReceiveTimestamp( ).GetLocalTimeString( )
				<< " ("	<< static_cast<Bit::Float64>( header3.GetReceiveTimestamp( ).GetFractions( ) ) / static_cast<Bit::Float64>( 0xFFFFFFFF ) <<  ")"  << std::endl;
	std::cout << std::endl;
	std::cout << " Transmit time       : " << header3.GetTransmitTimestamp( ).GetTimeString( )
				<< " ("	<< static_cast<Bit::Float64>( header3.GetTransmitTimestamp( ).GetFractions( ) ) / static_cast<Bit::Float64>( 0xFFFFFFFF ) <<  ")"  << std::endl;
	std::cout << " Transmit local time : " << header3.GetTransmitTimestamp( ).GetLocalTimeString( )
				<< " ("	<< static_cast<Bit::Float64>( header3.GetTransmitTimestamp( ).GetFractions( ) ) / static_cast<Bit::Float64>( 0xFFFFFFFF ) <<  ")"  << std::endl;
	std::cout << std::endl;
	

	// Close the ntp client
	ntp.Close( );
	
	// Print the finish text
	std::cout << "Finished NTP Test." << std::endl;
	std::cout << "-------------------------------------------" << std::endl;
	
}
Beispiel #28
0
 void connectToServer(const std::string& address) {
     NetAddress serverAddress(address + format(":%d", PORT));
     m_conversationArray.append(shared_ptr<Conversation>(new Conversation(this, NetConnection::connectToServer(serverAddress))));
 }
int ClientServerMain()
{
    LocalMatcher matcher;

    uint64_t clientId = 1;

    uint8_t connectTokenData[ConnectTokenBytes];
    uint8_t connectTokenNonce[NonceBytes];

    uint8_t clientToServerKey[KeyBytes];
    uint8_t serverToClientKey[KeyBytes];

    int numServerAddresses;
    Address serverAddresses[MaxServersPerConnectToken];

    memset( connectTokenNonce, 0, NonceBytes );

    if ( !matcher.RequestMatch( clientId, connectTokenData, connectTokenNonce, clientToServerKey, serverToClientKey, numServerAddresses, serverAddresses ) )
    {
        printf( "error: request match failed\n" );
        return 1;
    }

    ClientServerPacketFactory packetFactory;

    Address clientAddress( "::1", ClientPort );
    Address serverAddress( "::1", ServerPort );

    GameNetworkTransport clientTransport( packetFactory, clientAddress );
    GameNetworkTransport serverTransport( packetFactory, serverAddress );

    if ( clientTransport.GetError() != SOCKET_ERROR_NONE || serverTransport.GetError() != SOCKET_ERROR_NONE )
    {
        printf( "error: failed to initialize sockets\n" );
        return 1;
    }
    
    const int NumIterations = 20;

    double time = 0.0;

    GameClient client( GetDefaultAllocator(), clientTransport );

    GameServer server( GetDefaultAllocator(), serverTransport );

    server.SetServerAddress( serverAddress );

    server.Start();
    
    client.Connect( serverAddress, connectTokenData, connectTokenNonce, clientToServerKey, serverToClientKey );

    for ( int i = 0; i < NumIterations; ++i )
    {
        client.SendPackets();
        server.SendPackets();

        clientTransport.WritePackets();
        serverTransport.WritePackets();

        clientTransport.ReadPackets();
        serverTransport.ReadPackets();

        client.ReceivePackets();
        server.ReceivePackets();

        client.CheckForTimeOut();
        server.CheckForTimeOut();

        if ( client.ConnectionFailed() )
        {
            printf( "error: client connect failed!\n" );
            break;
        }

        if ( client.IsConnected() && server.GetNumConnectedClients() == 1 )
            client.Disconnect();

        time += 0.1f;

        if ( !client.IsConnecting() && !client.IsConnected() && server.GetNumConnectedClients() == 0 )
            break;

        client.AdvanceTime( time );
        server.AdvanceTime( time );

        clientTransport.AdvanceTime( time );
        serverTransport.AdvanceTime( time );
    }

    client.Disconnect();

    server.Stop();

    return 0;
}
Beispiel #30
0
int main(int argc, char ** argv)
{
	int status = EXIT_FAILURE;

	try
	{
		avatar::AppEnvironment env(argc, argv);
		avatar::cmdline_utils::Parser cmdlineParser;
		std::unique_ptr<avatar::RiftApp> app;

		auto cmdlineParserResult = cmdlineParser.parseOptions();

		switch (cmdlineParserResult.first)
		{

			case avatar::cmdline_utils::Parser::Status::LaunchColorCubeDemo:
			{
				std::wcout << L"Info >> description: launching color cube demo" << std::endl;
				app.reset(new avatar::ColorCubeApp);
			}
			break;

			case avatar::cmdline_utils::Parser::Status::LaunchTextureCubeDemo:
			{
				std::wcout << L"Info >> description: launching texture cube demo" << std::endl;
				app.reset(new avatar::TexCubeApp);
			}
			break;

			case avatar::cmdline_utils::Parser::Status::LaunchMonoWebcamDemo:
			{
				std::wcout << L"Info >> description: launching mono webcam demo" << std::endl;
				app.reset(new avatar::WebcamMonoApp);
			}
			break;

			case avatar::cmdline_utils::Parser::Status::LaunchStereoWebcamDemo:
			{
				std::wcout << L"Info >> description: launching stereo webcam demo" << std::endl;
				app.reset(new avatar::WebcamStereoApp);
			}
			break;

			case avatar::cmdline_utils::Parser::Status::LaunchClientDemo:
			{
				QString const serverAddressString = cmdlineParser.value(avatar::cmdline_utils::launchClientDemo);
				QHostAddress serverAddress(serverAddressString);

				std::wcout << L"Info >> description: launching client demo with server IP address " << serverAddressString.toStdWString() << std::endl;

				app.reset(new avatar::VideoStreamClientApp(serverAddress));
			}
			break;

			case avatar::cmdline_utils::Parser::Status::LaunchServerDemo:
			{
				std::wcout << L"Info >> description: launching server demo" << std::endl;
				app.reset(new avatar::VideoStreamServerApp);
			}
			break;

			case avatar::cmdline_utils::Parser::Status::LaunchFirstPersonViewDemo:
			{
				std::wcout << L"Info >> description: launching FPV demo" << std::endl;
				app.reset(new avatar::FirstPersonViewApp());
			}
			break;

			case avatar::cmdline_utils::Parser::Status::ShowHelp:
			{
				cmdlineParser.showHelp(EXIT_SUCCESS); // showHelp() will exit the application
			}
			break;

			case avatar::cmdline_utils::Parser::Status::Error:
			{
				std::wcout << cmdlineParserResult.second.toStdWString() << std::endl;
				cmdlineParser.showHelp(EXIT_FAILURE); // showHelp() will exit the application
			}
			break;

			default:
			{
				Q_ASSERT(false);
				cmdlineParser.showHelp(EXIT_FAILURE); // showHelp() will exit the application
			}

		}

		app->show();
		status = env.exec();

	}
	catch (avatar::Exception const & e)
	{
		std::wcout << e.what().toStdWString() << std::endl;
	}

	return status;
}