Exemple #1
0
    extern void CreateSession(const std::string& token, SessionCallback callback) {
        std::string url = generateSignedUrl(GET_SESSION, { { "token", token } });

        auto client = createClient();
        client->Url(url)
            .Mode(LastFmClient::Thread::Background)
            .Run([token, callback](LastFmClient* client, int statusCode, CURLcode curlCode) {
                Session session;
                session.token = token;

                if (statusCode == 200) {
                    try {
                        auto json = nlohmann::json::parse(client->Stream().str());
                        auto subscriber = json["session"];
                        session.username = subscriber.value("name", "");
                        session.sessionId = subscriber.value("key", "");
                    }
                    catch (...) {
                        /* not much we can do... */
                    }
                }

                validate(session);
                callback(session);
        });
    }
// 录制线程
void *thread_recording(void*)
{
    TaskScheduler* scheduler = BasicTaskScheduler::createNew();
    env = BasicUsageEnvironment::createNew(*scheduler);
    gettimeofday(&startTime, NULL);
    streamURL = rtspPath;
    // Create (or arrange to create) our client object:
    if (createHandlerServerForREGISTERCommand) {
        handlerServerForREGISTERCommand
            = HandlerServerForREGISTERCommand::createNew(*env, continueAfterClientCreation0, handlerServerForREGISTERCommandPortNum, authDBForREGISTER,  verbosityLevel, progName);
        if (handlerServerForREGISTERCommand == NULL) {
            *env << "Failed to create a server for handling incoming \"REGISTER\" commands: " << env->getResultMsg() << "\n";
        } else {
            *env << "Awaiting an incoming \"REGISTER\" command on port " << handlerServerForREGISTERCommand->serverPortNum() << "\n";
        }
    } else {
        ourClient = createClient(*env, streamURL, verbosityLevel, progName);
        if (ourClient == NULL) {
            *env << "Failed to create " << clientProtocolName << " client: " << env->getResultMsg() << "\n";
            shutdown();
        }
        ALOG(TX_LOG_INFO, TAG,"client create success\n");
        continueAfterClientCreation1();
    }
    env->taskScheduler().doEventLoop();
}
static void acceptCommonHandler(int fd, int flags) {
    client *c;
    if ((c = createClient(fd)) == NULL) {
        Log(WARNING,
            "Error registering fd event for the new client: %s (fd=%d)",
            strerror(errno),fd);
        close(fd); /* May be already closed, just ignore errors */
        return;
    }
    /* If maxclient directive is set and this is one client more... close the
     * connection. Note that we create the client instead to check before
     * for this condition, since now the socket is already set in non-blocking
     * mode and we can send an error for free using the Kernel I/O */
    if (listLength(server.clients) > server.maxclients) {
        char *err = "-ERR max number of clients reached\r\n";

        /* That's a best effort error message, don't check write errors */
        if (write(c->fd,err,strlen(err)) == -1) {
            /* Nothing to do, Just to avoid the warning... */
        }
        server.stat_rejected_conn++;
        freeClient(c);
        return;
    }
    server.stat_numconnections++;
    c->flags |= flags;
}
Exemple #4
0
err_t TcpServer::onAccept(tcp_pcb *clientTcp, err_t err)
{
	// Anti DDoS :-)
	if (system_get_free_heap_size() < 6500)
	{
		debugf("\r\n\r\nCONNECTION DROPPED\r\n\t(%d)\r\n\r\n", system_get_free_heap_size());
		return ERR_MEM;
	}

	#ifdef NETWORK_DEBUG
	debugf("onAccept state: %d K=%d", err, totalConnections);
	list_mem();
	#endif

	if (err != ERR_OK)
	{
		//closeTcpConnection(clientTcp, NULL);
		return err;
	}

	TcpConnection* client = createClient(clientTcp);
	if (client == NULL) return ERR_MEM;
	client->setTimeOut(timeOut);
	onClient((TcpClient*)client);

	return ERR_OK;
}
SimpleMenu::SimpleMenu(QWidget* parent, WelcomeScreen* screen)
: QObject(parent)
, m_screen(screen)
, m_protocol(0)
, m_state(READY)
, m_player1(0)
, m_player2(0)
{
    if (m_screen) {
        // create buttons
        m_server_btn = m_screen->addButton(0, 0, QIcon(QLatin1String(iconServer)),
                                           tr("Host Game"));
        m_client_btn = m_screen->addButton(0, 1, QIcon(QLatin1String(iconClient)),
                                           tr("Connect to Game"));

        // create connections
        connect(m_server_btn, SIGNAL(clicked()),
            this, SLOT(createServer()));
        connect(m_client_btn, SIGNAL(clicked()),
            this, SLOT(createClient()));

        // WiFi direct
        wpa = new Wpa;
        wpa->setEnabled(true);

        QVariantMap args;
        args["DeviceName"] = QHostInfo::localHostName();
        const char dev_type[8] = {0x00, 0x09, 0x00, 0x50, 0xf2, 0x04, 0x00, 0x05};
        args["PrimaryDeviceType"] = QByteArray(dev_type, 8);
        wpa->setProperties(args);
    }
}
Exemple #6
0
/**
 * Main program
 * @return 
 */
int main(int argc, char** argv) {

    
    // document root
    char* docroot = open_documentroot(argc, argv);


    int server = creer_serveur(WEBSERVER_PORT);
    printf("Server launched:\n");

    // Mimes
    loadMimes();
    
    // Load stats
    init_stats();
    
    
    // Signaux
    initialiser_signaux();

    
    /**
     * Get client request
     * @return 
     */
    createClient(server, docroot);

    return 0;

}
Exemple #7
0
void MultipleBotConnection::connectTimerSlot()
{
    const auto connexionCountVar=connexionCountTarget();
    if(apiToCatchChallengerClient.size()<connexionCountVar && numberOfBotConnected<connexionCountVar)
    {
        if(numberOfBotConnected<numberOfSelectedCharacter)
        {
            qDebug() << "MultipleBotConnection::connectTimerSlot(): numberOfBotConnected(" << numberOfBotConnected << ")<numberOfSelectedCharacter(" << numberOfSelectedCharacter << ")";
            haveEnError=true;
            connectTimer.stop();
        }
        else
        {
            //qDebug() << "MultipleBotConnection::connectTimerSlot(): ping";
            const quint32 &diff=numberOfBotConnected-numberOfSelectedCharacter;
            if(diff<=(quint32)maxDiffConnectedSelected())
            {
                createClient();
                qDebug() << "MultipleBotConnection::connectTimerSlot(): createClient()";
            }
        }
    }
    else
    {
        qDebug() << "MultipleBotConnection::connectTimerSlot(): finish, stop it";
        emit emit_all_player_connected();
        connectTimer.stop();
    }
}
/**
 * @brief Set the value of a characteristic of a service on a remote device.
 * @param [in] bdAddress
 * @param [in] serviceUUID
 * @param [in] characteristicUUID
 */
/* STATIC */ void BLEDevice::setValue(BLEAddress bdAddress, BLEUUID serviceUUID, BLEUUID characteristicUUID, std::string value) {
	ESP_LOGD(LOG_TAG, ">> setValue: bdAddress: %s, serviceUUID: %s, characteristicUUID: %s", bdAddress.toString().c_str(), serviceUUID.toString().c_str(), characteristicUUID.toString().c_str());
	BLEClient *pClient = createClient();
	pClient->connect(bdAddress);
	pClient->setValue(serviceUUID, characteristicUUID, value);
	pClient->disconnect();
} // setValue
Exemple #9
0
int main(int argc, char** argv)
{
    if (usage(argc, argv) == false)
        return -1;
    
    TaskScheduler* scheduler = BasicTaskScheduler::createNew();
    env = BasicUsageEnvironment::createNew(*scheduler);
    
    progName = argv[0];
    verbosityLevel = 1;
    playContinuously = True;
    sendOptionsRequest = True;
    notifyOnPacketArrival = True;
    streamURL = argv[1];
    
    gettimeofday(&startTime, NULL);
    
    ourClient = createClient(*env, streamURL, verbosityLevel, progName);
    if (ourClient == NULL)
    {
        *env << "Failed to create " << clientProtocolName << " client: " << env->getResultMsg() << "\n";
        shutdown();
    }
    
    if (sendOptionsRequest)
        getOptions(continueAfterOPTIONS);
    
    else
        continueAfterOPTIONS(NULL, 0, NULL);
    
    env->taskScheduler().doEventLoop();
    return 0;
}
Exemple #10
0
void Worker::onConnection(int fd, int ev, void *data)
{
	//check maxclients
	Config *pConfig = Config::getInstance();
	if(pMaster->pGlobals->clients >= pConfig->nMaxClients){
		LOG("Connection is full");
		close(fd);
		return ;
	}
	
	//ip and port
	struct sockaddr_in *pAddr = (struct sockaddr_in*)data;
	char ip[17]; 
	int port = ntohs(pAddr->sin_port);
	memset(ip, 0, sizeof(ip));
	inet_ntop(AF_INET, &pAddr->sin_addr, ip, 16);
	
	//create client
	createClient(fd, ip, port);
	
	//free accept lock
	if(pMaster->bUseAcceptMutex && 
		UnLockAcceptMutex(&pMaster->pGlobals->lock, nPid))
	{
		//LOG("unlock accept mutex");
		bHeldAcceptLock = false;
		pServer->stop();
	}
}
    bool openClient (const double newSampleRate, const BitArray& newChannels)
    {
        sampleRate = newSampleRate;
        channels = newChannels;
        channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
        numChannels = channels.getHighestBit() + 1;

        if (numChannels == 0)
            return true;

        client = createClient();

        if (client != 0
             && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
                  || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
        {
            channelMaps.clear();
            for (int i = 0; i <= channels.getHighestBit(); ++i)
                if (channels[i])
                    channelMaps.add (i);

            REFERENCE_TIME latency;
            if (OK (client->GetStreamLatency (&latency)))
                latencySamples = wasapi_refTimeToSamples (latency, sampleRate);

            (void) OK (client->GetBufferSize (&actualBufferSize));

            return OK (client->SetEventHandle (clientEvent));
        }

        return false;
    }
Exemple #12
0
/*
 * Start of the ssl client
 * There is a main thread and a receive thread
 * Main:
 *
 * Recv:
 */
main() {
	int status;
	pthread_t recvThread;
	pthread_t fsmThread;
	sslStruct *sslC;

	// For now this is just a function where we set all variables
	// Ultimately this should be read from a resource file
	initCfg();
	// Connect to Unit under Test (UT)
	initConnectionToServer();
	// Ctrl-Z to give stats
	initSignals();

	status = pthread_create(&recvThread, NULL, &recvFunction, (void*)NULL);
	if (status != 0) {
		perror("Start Thread Error:"); return -1;
	}
	status = pthread_create(&fsmThread, NULL, &fsmFunction, (void*)NULL);
	if (status != 0) {
		perror("Start Thread Error:"); return -1;
	}
	fflush(stdout);

	// For now just create 1 Client to test Server
	sslC = createClient();
	if (sslC == NULL)
		return -1;
	sendHello(sslC);
	while(1);
}
Exemple #13
0
void acceptHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
    int cport, cfd;
    char cip[128];
    redisClient *c;
    REDIS_NOTUSED(el);
    REDIS_NOTUSED(mask);
    REDIS_NOTUSED(privdata);

    cfd = anetAccept(server.neterr, fd, cip, &cport);
    if (cfd == AE_ERR) {
        redisLog(REDIS_VERBOSE,"Accepting client connection: %s", server.neterr);
        return;
    }
    redisLog(REDIS_VERBOSE,"Accepted %s:%d", cip, cport);
    if ((c = createClient(cfd)) == NULL) {
        redisLog(REDIS_WARNING,"Error allocating resoures for the client");
        close(cfd); /* May be already closed, just ingore errors */
        return;
    }
    /* If maxclient directive is set and this is one client more... close the
     * connection. Note that we create the client instead to check before
     * for this condition, since now the socket is already set in nonblocking
     * mode and we can send an error for free using the Kernel I/O */
    if (server.maxclients && listLength(server.clients) > server.maxclients) {
        char *err = "-ERR max number of clients reached\r\n";

        /* That's a best effort error message, don't check write errors */
        if (write(c->fd,err,strlen(err)) == -1) {
            /* Nothing to do, Just to avoid the warning... */
        }
        freeClient(c);
        return;
    }
    server.stat_numconnections++;
}
Exemple #14
0
/* ====================================================================
 * Bring up / Teardown
 * ==================================================================== */
void *load() {
    g.c = newFakeClient();
    g.c_noreturn = createClient(-1);
    g.err_parse = createObject(
        REDIS_STRING,
        sdsnew("-ERR JSON Parse Error.  You can debug with JSONDOCVALIDATE."));
    return NULL;
}
void DXDB_initServer() {                   //printf("DXDB_initServer\n");
    server.alc.RestClient         = createClient(-1);
    server.alc.RestClient->flags |= REDIS_LUA_CLIENT;
    aeCreateTimeEvent(server.el, 1, luaCronTimeProc, NULL, NULL);
    initX_DB_Range(); initAccessCommands(); init_six_bit_strings();
    init_DXDB_PersistentStorageItems(INIT_MAX_NUM_TABLES, INIT_MAX_NUM_INDICES);
    initServer_Extra();
}
UtlBoolean SipProtocolServerBase::send(SipMessage* message,
                            const char* hostAddress,
                            int hostPort)
{
    UtlBoolean sendOk = FALSE;


    UtlString localIp(message->getLocalIp());
    
    if (localIp.length() < 1)
    {
        localIp = mDefaultIp;
    }

    SipClient* client = createClient(hostAddress, hostPort, localIp);
    if(client)
    {
        int isBusy = client->isInUseForWrite();
        UtlString clientNames;

        client->getClientNames(clientNames);
        OsSysLog::add(FAC_SIP, PRI_DEBUG, "Sip%sServerBase::send %p isInUseForWrite %d, client info\n %s",
                mProtocolString.data(), client, isBusy, clientNames.data());

        sendOk = client->sendTo(*message, hostAddress, hostPort);
        if(!sendOk)
        {
            OsTask* pCallingTask = OsTask::getCurrentTask();
            OsTaskId_t callingTaskId = -1;
            OsTaskId_t clientTaskId = -1;

            if ( pCallingTask )
            {
               pCallingTask->id(callingTaskId);
            }
            client->id(clientTaskId);

            if (clientTaskId != callingTaskId)
            {
               // Do not need to clientLock.acquireWrite();
               // as deleteClient uses the locking list lock
               // which is all that is needed as the client is
               // already marked as busy when we called
               // createClient above.
               deleteClient(client);
               client = NULL;
            }
        }
    }

        if(client)
        {
            releaseClient(client);
        }

    return(sendOk);
}
/**
 * @brief Get the value of a characteristic of a service on a remote device.
 * @param [in] bdAddress
 * @param [in] serviceUUID
 * @param [in] characteristicUUID
 */
/* STATIC */ std::string BLEDevice::getValue(BLEAddress bdAddress, BLEUUID serviceUUID, BLEUUID characteristicUUID) {
	ESP_LOGD(LOG_TAG, ">> getValue: bdAddress: %s, serviceUUID: %s, characteristicUUID: %s", bdAddress.toString().c_str(), serviceUUID.toString().c_str(), characteristicUUID.toString().c_str());
	BLEClient *pClient = createClient();
	pClient->connect(bdAddress);
	std::string ret = pClient->getValue(serviceUUID, characteristicUUID);
	pClient->disconnect();
	ESP_LOGD(LOG_TAG, "<< getValue");
	return ret;
} // getValue
int main(int argc, char* argv[]) {
	int local_port;
	char* local_interface;
	char* remote_host;
	int remote_port;
	int isClient = 0;

	if (argc < 3 || argc > 4) {
		perror("Error: improper number of args entered\nProper format: ./cs352proxy <port> <local_interface> or ./cs352proxy <remote_host> <remote_port> <local_interface>\n");
		return 0;
	} else if (argc == 3) {
		local_port = atoi(argv[1]);
		if (local_port < 1024 || local_port > 65536) {
			printf("port out of range\n");
			return 1;
		}
		local_interface = argv[2];
		isClient = 0;
	} else {
		remote_host = argv[1];
		remote_port = atoi(argv[2]);
		if (remote_port < 1024 || remote_port > 65536) {
			printf("port out of range\n");
			return 1;
		}
		local_interface = argv[3];
		isClient = 1;
	}

	if ( (tap_fd = allocate_tunnel(local_interface, IFF_TAP | IFF_NO_PI)) < 0) {
		perror("Opening tap interface failed! \n");
		exit(1);
	}

	int socketfd = socket(AF_INET, SOCK_STREAM, 0);
	if (socketfd < 0) {
		perror("Socket failed");
		exit(1);
	}

	if (!isClient) {
		TCPSocketfd = createServer(socketfd, local_port);
	} else {
		TCPSocketfd = createClient(socketfd, remote_port, remote_host);
	}

	pthread_t TAPthread, TCPthread;

	pthread_create(&TAPthread, NULL, TAPHandle, NULL);
	pthread_create(&TCPthread, NULL, TCPHandle, NULL);

 	pthread_join(TAPthread, NULL);
	pthread_join(TCPthread, NULL);

	return 0;
}
Exemple #19
0
void MainWindow::setupActions()
{
    KStandardGameAction::gameNew(m_main, SLOT(newGame()), actionCollection());
    KStandardGameAction::restart(m_main, SLOT(restart()), actionCollection());
    KStandardGameAction::highscores(m_main, SLOT(highscores()), actionCollection());
    
    KStandardGameAction::quit(this, SLOT(close()), actionCollection());
    
    QAction* action;
    action = new QAction(i18n("&Single Player"), this);
    action->setIcon(QIcon::fromTheme( QLatin1String( SimpleMenu::iconLocal)));
    actionCollection()->addAction("game_local", action);
    connect(action, SIGNAL(triggered()), m_main, SLOT(localGame()));
    action = new QAction(i18n("&Host Game..."), this);
    action->setIcon(QIcon::fromTheme( QLatin1String( SimpleMenu::iconServer)));
    actionCollection()->addAction("game_create_server", action);
    connect(action, SIGNAL(triggered()), m_main, SLOT(createServer()));
    action = new QAction(i18n("&Connect to Game..."), this);
    action->setIcon(QIcon::fromTheme( QLatin1String( SimpleMenu::iconClient))),
    actionCollection()->addAction("game_create_client", action);
    connect(action, SIGNAL(triggered()), m_main, SLOT(createClient()));
    // settings
    action = new QAction(i18n("Change &Nickname..."), this);
    actionCollection()->addAction("options_nickname", action);
    connect(action, SIGNAL(triggered()), m_main, SLOT(changeNick()));
    action = new KToggleAction(i18n("&Play Sounds"), this);
    actionCollection()->addAction("options_sounds", action);
    connect(action, SIGNAL(triggered(bool)), m_main, SLOT(toggleSounds(bool)));
    // This action will be disabled when a game is being run
    action = new KToggleAction(i18n("&Adjacent Ships"), this);
    action->setChecked(Settings::adjacentShips());
    actionCollection()->addAction("options_adjacent", action);
    connect(action, SIGNAL(triggered(bool)), m_main, SLOT(toggleAdjacent(bool)));
    // This action will be disabled when a game is being run
    action = new KToggleAction(i18n("&Multiple Ships"), this);
    action->setChecked(Settings::severalShips());
    actionCollection()->addAction("options_multiple_ships", action);
    connect(action, SIGNAL(triggered(bool)), m_main, SLOT(toggleMultiple(bool)));
    // config end of game message
    action = new KToggleAction(i18n("Show End-of-Game Message"), this);
    action->setChecked(true);
    actionCollection()->addAction("options_show_endgame_message", action);
    connect(action, SIGNAL(triggered(bool)), m_main, SLOT(toggleEndOfGameMessage(bool)));
    // actions for grid
    action = new KToggleAction(i18n("Show &Left Grid"), this);
    action->setChecked(true);
    actionCollection()->addAction("options_showleftgrid", action);
    connect(action, SIGNAL(triggered(bool)), m_main, SLOT(toggleLeftGrid(bool)));
    action = new KToggleAction(i18n("Show &Right Grid"), this);
    action->setChecked(true);
    actionCollection()->addAction("options_showrightgrid", action);
    connect(action, SIGNAL(triggered(bool)), m_main, SLOT(toggleRightGrid(bool)));
    
    setupGUI();
}
CWizDocumentView::CWizDocumentView(CWizExplorerApp& app, QWidget* parent)
    : QWidget(parent)
    , m_app(app)
    , m_userSettings(app.userSettings())
    , m_dbMgr(app.databaseManager())
    , m_title(new CWizTitleBar(app, this))
    , m_web(new CWizDocumentWebView(app, this))
    , m_client(NULL)
    , m_tags(NULL)
    , m_attachments(NULL)
    , m_editingDocument(true)
    , m_viewMode(app.userSettings().noteViewMode())
{
    m_client = createClient();

    QVBoxLayout* layout = new QVBoxLayout(this);
    setLayout(layout);
    layout->addWidget(m_client);
    layout->setContentsMargins(0, 0, 0, 0);

    m_title->setEditingDocument(m_editingDocument);

    m_timerDelay.setSingleShot(true);
    connect(&m_timerDelay, SIGNAL(timeout()), SLOT(on_titleEdit_textEdit_writeDelay()));

    connect(m_title->titleEdit(), SIGNAL(textChanged(const QString&)), \
            SLOT(on_titleEdit_textChanged(const QString&)));

    connect(m_title->editDocumentButton(), SIGNAL(clicked()), \
            SLOT(on_editDocumentButton_clicked()));

    connect(m_title->tagsButton(), SIGNAL(clicked()), \
            SLOT(on_tagsButton_clicked()));

    connect(m_title->attachmentButton(), SIGNAL(clicked()), \
            SLOT(on_attachmentButton_clicked()));

    connect(m_title->infoButton(), SIGNAL(clicked()), \
            SLOT(on_infoButton_clicked()));

    qRegisterMetaType<WIZDOCUMENTDATA>("WIZDOCUMENTDATA");
    qRegisterMetaType<WIZDOCUMENTATTACHMENTDATA>("WIZDOCUMENTATTACHMENTDATA");

    connect(&m_dbMgr, SIGNAL(documentModified(const WIZDOCUMENTDATA&, const WIZDOCUMENTDATA&)), \
            SLOT(on_document_modified(const WIZDOCUMENTDATA&, const WIZDOCUMENTDATA&)));

    connect(&m_dbMgr, SIGNAL(attachmentCreated(const WIZDOCUMENTATTACHMENTDATA&)), \
            SLOT(on_attachment_created(const WIZDOCUMENTATTACHMENTDATA&)));

    connect(&m_dbMgr, SIGNAL(attachmentDeleted(const WIZDOCUMENTATTACHMENTDATA&)), \
            SLOT(on_attachment_deleted(const WIZDOCUMENTATTACHMENTDATA&)));
}
    WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& d, const bool exclusiveMode)
        : device (d),
          sampleRate (0),
          defaultSampleRate (0),
          numChannels (0),
          actualNumChannels (0),
          minBufferSize (0),
          defaultBufferSize (0),
          latencySamples (0),
          useExclusiveMode (exclusiveMode),
          sampleRateHasChanged (false)
    {
        clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));

        ComSmartPtr <IAudioClient> tempClient (createClient());
        if (tempClient == nullptr)
            return;

        REFERENCE_TIME defaultPeriod, minPeriod;
        if (! check (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
            return;

        WAVEFORMATEX* mixFormat = nullptr;
        if (! check (tempClient->GetMixFormat (&mixFormat)))
            return;

        WAVEFORMATEXTENSIBLE format;
        copyWavFormat (format, mixFormat);
        CoTaskMemFree (mixFormat);

        actualNumChannels = numChannels = format.Format.nChannels;
        defaultSampleRate = format.Format.nSamplesPerSec;
        minBufferSize = refTimeToSamples (minPeriod, defaultSampleRate);
        defaultBufferSize = refTimeToSamples (defaultPeriod, defaultSampleRate);

        rates.addUsingDefaultSort (defaultSampleRate);

        static const int ratesToTest[] = { 44100, 48000, 88200, 96000, 176400, 192000 };

        for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
        {
            if (ratesToTest[i] == defaultSampleRate)
                continue;

            format.Format.nSamplesPerSec = (DWORD) ratesToTest[i];

            if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
                                                          (WAVEFORMATEX*) &format, 0)))
                if (! rates.contains (ratesToTest[i]))
                    rates.addUsingDefaultSort (ratesToTest[i]);
        }
    }
static void createMissingClients(client c) {
    int n = 0;

    while(config.liveclients < config.numclients) {
        createClient(NULL,0,c);

        /* Listen backlog is quite limited on most systems */
        if (++n > 64) {
            usleep(50000);
            n = 0;
        }
    }
}
Exemple #23
0
int main(int argc, char *argv[]) {
    ServiceSpec *specification = (ServiceSpec *)parseServiceSpec("../../examples/serviceSpecs/temperatureServiceMQTT.json");
    CommHandle *commHandle = createClient(specification);

    if (commHandle) {
        Context context;
        context.name = "topic";
        context.value = "temperature";
        commHandle->send("75 degrees", context);
        commHandle->unsubscribe("temperature");
        commHandle->subscribe("temperature");
    }
}
static void createMissingClients(client c) {
    int n = 0;

    while(config.liveclients < config.numclients) {
        createClient(c->obuf,sdslen(c->obuf)/config.pipeline);

        /* Listen backlog is quite limited on most systems */
        if (++n > 64) {
            usleep(50000);
            n = 0;
        }
    }
}
    WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_)
        : device (device_),
          sampleRate (0),
          numChannels (0),
          actualNumChannels (0),
          defaultSampleRate (0),
          minBufferSize (0),
          defaultBufferSize (0),
          latencySamples (0)
    {
        clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));

        ComSmartPtr <IAudioClient> tempClient (createClient());
        if (tempClient == 0)
            return;

        REFERENCE_TIME defaultPeriod, minPeriod;
        if (! OK (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
            return;

        WAVEFORMATEX* mixFormat = 0;
        if (! OK (tempClient->GetMixFormat (&mixFormat)))
            return;

        WAVEFORMATEXTENSIBLE format;
        wasapi_copyWavFormat (format, mixFormat);
        CoTaskMemFree (mixFormat);

        actualNumChannels = numChannels = format.Format.nChannels;
        defaultSampleRate = format.Format.nSamplesPerSec;
        minBufferSize = wasapi_refTimeToSamples (minPeriod, defaultSampleRate);
        defaultBufferSize = wasapi_refTimeToSamples (defaultPeriod, defaultSampleRate);

        FloatElementComparator<double> comparator;
        rates.addSorted (comparator, defaultSampleRate);

        static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };

        for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
        {
            if (ratesToTest[i] == defaultSampleRate)
                continue;

            format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);

            if (SUCCEEDED (tempClient->IsFormatSupported (AUDCLNT_SHAREMODE_SHARED, (WAVEFORMATEX*) &format, 0)))
                if (! rates.contains (ratesToTest[i]))
                    rates.addSorted (comparator, ratesToTest[i]);
        }
    }
Exemple #26
0
void MyServerSocket::onAccept(sockaddr_in * addr, int handle){

	uLong user_id = (addr->sin_addr).s_addr;
	ClientSocket * socket = createClient((addr->sin_addr).s_addr, inet_ntoa(addr->sin_addr), ntohs(addr->sin_port));
	socket->OnAccept(handle);
	socket->status = socket_ready;
	socket->s_status = session_connect;
	/*  成功赋值了  为何?*/
	socket->Recevice();
	/*
	add sessions
	*/
	//clients.insert(ScoketPair(user_id, socket));
}
	void start(BundleContext::Ptr pContext)
	{
		_pContext = pContext;
		_pPrefs = ServiceFinder::find<PreferencesService>(pContext);
		
		Poco::Util::AbstractConfiguration::Keys keys;
		_pPrefs->configuration()->keys("mqtt.clients", keys);
		for (std::vector<std::string>::const_iterator it = keys.begin(); it != keys.end(); ++it)
		{
			std::string baseKey = "mqtt.clients.";
			baseKey += *it;
			createClient(baseKey, *it);
		}
	}
static int 
acceptClient(int handle, void *context) 
{
  int newHandle = 0;
  int opts;
  struct sockaddr_in6 addr;
  socklen_t addrlen = sizeof(addr);

  newHandle = accept(handle, (struct sockaddr *) &addr, &addrlen);
  if (newHandle < 0) { 
    perror("accept");
    goto error;
  }

  opts = fcntl(newHandle, F_GETFL);
  if (opts < 0) {
    perror("fcntl(F_GETFL)");
    goto error;
  }  

  opts = opts | O_NONBLOCK;
  if (fcntl(newHandle, F_SETFL, opts) < 0) {
    perror("fcntl(F_SETFL)");
    goto error;
  }

  ClientRef client = createClient(newHandle);
  if (client == NULL) {
    fputs("failed to create client\n", stderr);
    goto error;
  }

  fprintf(stdout, "client [%s]:%d connected\n", 
      addrtostr((struct sockaddr *) &addr, addrlen, NULL, 0),
      addr.sin6_port);
          
  appendDescriptor(
      createDescriptor(newHandle, client, handleClient),
      (SocketDescriptorListRef) context);

  return 1;
  
error:
  if (client != NULL) disposeClient(client);
  if (newHandle >= 0) close(newHandle);
  return -1;
  
}
Exemple #29
0
bool CRTSPClient::Initialize()
{
  LogDebug("CRTSPClient::Initialize()");
  m_duration=7200*1000;
  TaskScheduler* scheduler = MPTaskScheduler::createNew();
  m_env = BasicUsageEnvironment::createNew(*scheduler);
	
  m_ourClient = createClient(*m_env, 0/*verbosityLevel*/, "TSFileSource");
  if (m_ourClient == NULL) 
  {
    LogDebug("Failed to create %s %s" ,clientProtocolName,m_env->getResultMsg() );
    shutdown();
    return false;
  }
  return true;
}
MQTTConnector::MQTTConnector(const std::string &host, const std::string &port,
		const std::string &user, const std::string &pass,
		const std::string &topicNamespace, const std::string &applicationId) :
		brokerHost(host), brokerPort(port), brokerUser(user), brokerPass(pass), mqttClient(
				NULL) {

	enabled = false;

	int processId = ibmras::common::port::getProcessId();
	unsigned long long time = ibmras::common::util::getMilliseconds();
	srand((unsigned int) time);

	std::stringstream clientIdStream;
	clientIdStream << "agent_" << rand();
	std::string clientId = clientIdStream.str();

	std::string namespacePrefix = topicNamespace;
	if (topicNamespace.length() > 0
			&& topicNamespace[topicNamespace.length() - 1] != '/') {
		namespacePrefix += '/';
	}

	std::stringstream rootTopicStream;
	rootTopicStream << namespacePrefix << AGENT_TOPIC_PREFIX << "/" << clientId;
	rootTopic = rootTopicStream.str();

	std::stringstream agentTopicStream;
	agentTopicStream << namespacePrefix << AGENT_TOPIC_PREFIX << "/agent/"
			<< clientId << "/";
	agentTopic = agentTopicStream.str();

	std::stringstream agentIdMessageStream;
	std::string applicationIdentifier;
	applicationIdentifier = ibmras::common::port::getHostName() + ":";
	applicationIdentifier += ibmras::common::itoa(processId);
	if (applicationId.length() > 0) {
		applicationIdentifier += ":" + applicationId;
	}
	agentIdMessageStream << rootTopic << "\n" << applicationIdentifier;
	agentIdMessage = agentIdMessageStream.str();

	willTopic = rootTopic + "/will";
	willMessage = agentIdMessage;
	createClient(clientId);

	IBMRAS_DEBUG_1(fine, "MQTTConnector: creating client: %s", clientId.c_str());
}