コード例 #1
0
void LoginDialog::accept()
{
	if(m_bLogin)
	{
		stopLogin();
		return;
	}
	QSettings settings;
	if (m_client)
	{
		startLogin();
		QString prev = m_client->getPreviousPassword();
		if (prev.isEmpty())
			m_client->setPreviousPassword(m_client->getPassword());
		m_client->setPassword(passwords[0]->text());
		unsigned status = m_client->getStatus();
		if (status == STATUS_OFFLINE)
			status = STATUS_ONLINE;
		m_client->setStatus(status, m_client->getCommonStatus());
		QDialog::accept();
		return;
	}

	getContacts()->clearClients();
    int n = cmbProfile->currentIndex();
	if(n == cmbProfile->count() - 1)
	{
		m_profile = QString::null;
		m_newProfile = true;
        m_newProfileName = e_newName->text();
        if(!ProfileManager::instance()->newProfile(m_newProfileName)) 
        {
            QMessageBox::information(NULL, i18n("Create Profile"), i18n("Error while creating a new profile"), QMessageBox::Ok);
            return;
        }
        ProfileManager::instance()->selectProfile(m_newProfileName);
		QDialog::accept();
		return;
	}
	if (n < 0) 
	{
		settings.setValue("SavePasswd", chkSave->isChecked());
		settings.setValue("NoShow", chkNoShow->isChecked());
		m_profile = QString::null;
		emit changeProfile(QString::null);
		QDialog::accept();
		return;
	}

	m_profile = cmbProfile->currentText();
	log(L_DEBUG, "Profile: %s", qPrintable(m_profile));
	settings.setValue("Profile", m_profile);
	settings.setValue("SavePasswd", chkSave->isChecked());
	settings.setValue("NoShow", chkNoShow->isChecked());

	// Probably, it shouldn't be here
	ProfileManager::instance()->selectProfile(m_profile);
	emit changeProfile(m_profile);

	ClientList clients;
	loadClients(m_profile, clients);
	clients.addToContacts();
	getContacts()->load();

	m_bLogin = false;
	unsigned j = 0;
	for (int i = 0; i < passwords.size(); i++)
	{
		Client *client = NULL;
		while (j < getContacts()->nClients())
		{
			client = getContacts()->getClient(j++);
			if ((client->protocol()->description()->flags & PROTOCOL_NO_AUTH) == 0)
				break;
			client = NULL;
		}
		if (client == NULL)
			break;
		client->setSavePassword(chkSave->isChecked());
		QString pswd = client->getPassword();
		QString new_pswd = passwords[i]->text();
		if (pswd != new_pswd)
		{
			QString prev = client->getPreviousPassword();
			if (!prev.isEmpty())
				client->setPreviousPassword(pswd);
			client->setPassword(new_pswd);
			m_bLogin = true;
		}
	}
	if(m_bLogin)
	{
		startLogin();
		for (int i = 0; i < passwords.size(); i++)
		{
			Client *client = getContacts()->getClient(i);
			unsigned status = client->getStatus();
			if (status == STATUS_OFFLINE)
				status = STATUS_ONLINE;
			client->setStatus(status, client->getCommonStatus());
		}
		QDialog::accept();
		return;
	}
	QDialog::accept();

}
コード例 #2
0
int main(int argc, char *argv[]) {
	Client client;
	client.start(argc, argv);
	return 0;
}
コード例 #3
0
bool MsgEdit::send()
{
    unsigned i;
    Contact *contact = getContacts()->contact(m_msg->contact());
    string client_str = m_msg->client();
    bool bSent = false;
    void *data = NULL;
    if (contact){
        Event e(EventMessageSend, m_msg);
        e.process();
        if (client_str.empty()){
            m_type = m_msg->type();
            Client *c = client(data, true, false, m_msg->contact(), (m_msg->getFlags() & MESSAGE_MULTIPLY) == 0);
            if (c){
                m_msg->setClient(c->dataName(data).c_str());
                bSent = c->send(m_msg, data);
            }else{
                data = NULL;
                for (i = 0; i < getContacts()->nClients(); i++){
                    Client *client = getContacts()->getClient(i);
                    if (client->send(m_msg, NULL)){
                        bSent = true;
                        break;
                    }
                }
            }
        }else{
            ClientDataIterator it(contact->clientData);
            while ((data = ++it) != NULL){
                if (it.client()->dataName(data) == client_str){
                    if (it.client()->send(m_msg, data))
                        bSent = true;
                    break;
                }
            }
        }
    }
    if (bSent){
        if (data){
            time_t now;
            time(&now);
            ((clientData*)data)->LastSend = now;
        }
    }else{
        if (m_msg){
            delete m_msg;
            m_msg = NULL;
        }
        stopSend();
        CToolButton *btnSend = NULL;
        Command cmd;
        cmd->id		= CmdSend;
        cmd->param	= this;
        Event e(EventCommandWidget, cmd);
        btnSend = (CToolButton*)(e.process());
        QWidget *msgWidget = btnSend;
        if (msgWidget == NULL)
            msgWidget = this;
        BalloonMsg::message(i18n("No such client for send message"), msgWidget);
        return false;
    }
    return true;
}
コード例 #4
0
bool CollectionShardingState::_checkShardVersionOk(OperationContext* txn,
                                                   string* errmsg,
                                                   ChunkVersion* expectedShardVersion,
                                                   ChunkVersion* actualShardVersion) const {
    Client* client = txn->getClient();

    // Operations using the DBDirectClient are unversioned.
    if (client->isInDirectClient()) {
        return true;
    }

    if (!repl::ReplicationCoordinator::get(txn)->canAcceptWritesForDatabase(_nss.db())) {
        // right now connections to secondaries aren't versioned at all
        return true;
    }

    const auto& oss = OperationShardingState::get(txn);

    // If there is a version attached to the OperationContext, use it as the received version.
    // Otherwise, get the received version from the ShardedConnectionInfo.
    if (oss.hasShardVersion()) {
        *expectedShardVersion = oss.getShardVersion(_nss);
    } else {
        ShardedConnectionInfo* info = ShardedConnectionInfo::get(client, false);
        if (!info) {
            // There is no shard version information on either 'txn' or 'client'. This means that
            // the operation represented by 'txn' is unversioned, and the shard version is always OK
            // for unversioned operations.
            return true;
        }

        *expectedShardVersion = info->getVersion(_nss.ns());
    }

    if (ChunkVersion::isIgnoredVersion(*expectedShardVersion)) {
        return true;
    }

    *actualShardVersion = (_metadata ? _metadata->getShardVersion() : ChunkVersion::UNSHARDED());

    if (expectedShardVersion->isWriteCompatibleWith(*actualShardVersion)) {
        return true;
    }

    //
    // Figure out exactly why not compatible, send appropriate error message
    // The versions themselves are returned in the error, so not needed in messages here
    //

    // Check epoch first, to send more meaningful message, since other parameters probably won't
    // match either.
    if (actualShardVersion->epoch() != expectedShardVersion->epoch()) {
        *errmsg = str::stream() << "version epoch mismatch detected for " << _nss.ns() << ", "
                                << "the collection may have been dropped and recreated";
        return false;
    }

    if (!actualShardVersion->isSet() && expectedShardVersion->isSet()) {
        *errmsg = str::stream() << "this shard no longer contains chunks for " << _nss.ns() << ", "
                                << "the collection may have been dropped";
        return false;
    }

    if (actualShardVersion->isSet() && !expectedShardVersion->isSet()) {
        *errmsg = str::stream() << "this shard contains versioned chunks for " << _nss.ns() << ", "
                                << "but no version set in request";
        return false;
    }

    if (actualShardVersion->majorVersion() != expectedShardVersion->majorVersion()) {
        // Could be > or < - wanted is > if this is the source of a migration, wanted < if this is
        // the target of a migration
        *errmsg = str::stream() << "version mismatch detected for " << _nss.ns();
        return false;
    }

    // Those are all the reasons the versions can mismatch
    MONGO_UNREACHABLE;
}
コード例 #5
0
ファイル: client.cpp プロジェクト: ChrisCarlsen/tortuga
int main(int argc, char* argv[])
{
	Client client;
	return client.main(argc, argv, "config.sub");
}
コード例 #6
0
ファイル: main.cpp プロジェクト: jwvg0425/ConsoleChat
int main(int argc, char* argv[])
{
	WSADATA wsaData;
	HANDLE hComPort;

	SOCKET hServSock;
	SOCKADDR_IN servAdr;
	DWORD flags = 0;

	if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
	{
		errorHandling("WSAStartup() error!");
		return -1;
	}

	hComPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);

	_beginthreadex(NULL, 0, IOCPThreadMain, (LPVOID)hComPort, 0, NULL);

	hServSock = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, WSA_FLAG_OVERLAPPED);
	
	if (hServSock == INVALID_SOCKET)
	{
		errorHandling("WSASocket() error!");
		return -1;
	}
	
	memset(&servAdr, 0, sizeof(servAdr));
	servAdr.sin_family = AF_INET;
	servAdr.sin_addr.s_addr = htonl(INADDR_ANY);
#ifdef _DEBUG
	servAdr.sin_port = htons(atoi("41026"));
#else
	if (argc != 2)
	{
		printf("USAGE : %s <PORT>", argv[0]);
		return;
	}

	servAdr.sin_port = htons(atoi(argv[1]));
#endif

	char option = 1;
	if (setsockopt(hServSock, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option)))
	{
		errorHandling("setsockopt() error!");
		return -1;
	}

	if (bind(hServSock, (SOCKADDR*)&servAdr, sizeof(servAdr)))
	{
		errorHandling("bind() error!");
		return -1;
	}

	if (listen(hServSock, 5))
	{
		errorHandling("bind() error!");
		return -1;
	}

	while (true)
	{
		SOCKET hClntSock;
		SOCKADDR_IN clntAdr;
		int addrLen = sizeof(clntAdr);

		hClntSock = accept(hServSock, (SOCKADDR*)&clntAdr, &addrLen);

		if (hClntSock == INVALID_SOCKET)
		{
			continue;
		}

		Client* client = new Client(hClntSock);

		if (CreateIoCompletionPort((HANDLE)hClntSock, hComPort, (ULONG_PTR)client, 0) != hComPort)
		{
			errorHandling("CreateIoCompletionPort() error!");
			continue;
		}

		ClientManager::getInstance()->addClient(client);

		client->connect();
	}

	ClientManager::releaseInstance();
	CloseHandle(hComPort);
	closesocket(hServSock);
	WSACleanup();

	return 0;

}
コード例 #7
0
ファイル: client.cpp プロジェクト: zhdtty/storm_net
int main(int argc, char** argv) {
	setDefaultConfigFile("client.conf");
	return g_server.run(argc, argv);
}
コード例 #8
0
ファイル: pomelocpp.cpp プロジェクト: xiyixia/pomelocpp
void Client::RequestCallback(const pc_request_t* req, int rc, const char* resp)
{
	pc_client_t* pc_client = pc_request_client(req);
	Client * client = (Client* )pc_client_ex_data(pc_client);
	client->RequestResponse(Request(req),rc,resp);
}
コード例 #9
0
ファイル: pomelocpp.cpp プロジェクト: xiyixia/pomelocpp
void Client::NotifyCallback(const pc_notify_t* notify, int rc)
{
	pc_client_t* pc_client = pc_notify_client(notify);
	Client * client = (Client* )pc_client_ex_data(pc_client);
	client->NotifyResponse(Notify(notify),rc);
}
コード例 #10
0
ファイル: l_client.cpp プロジェクト: EXio4/minetest
int ModApiClient::l_take_screenshot(lua_State *L)
{
	Client *client = getClient(L);
	client->makeScreenshot();
	return 0;
}
コード例 #11
0
ファイル: server.cpp プロジェクト: jmhain/csc464
void * serveClient(void *arg)
{
    Client *client = (Client *)arg;
    Packet *packet;
    char *filename;
    ifstream file;

    sendtoErr_init(errorPercent, DROP_ON, FLIP_ON, DEBUG_OFF, RSEED_ON);

    if ((filename = client->recvFilename()) == NULL) 
        return NULL;

    file.open(filename);
    if (!file.is_open()) {
        client->sendHeader(BADFILE);
        return NULL;
    } 

    client->sendHeader(GOODFILE);

    while (!file.eof()) {
        bool status = client->windowOpen();
        if (client->windowOpen()) {
            client->sendData(file);
        }

        if (client->wait(0, status ? 0 : 100000)) {
            packet = client->recvPacket();
            switch (packet->header->flag) {
            case RR:
                memcpy(&client->lastRR, packet->payload, 4);
                break;
            case SREJ:
                client->resendData(*(uint32_t *)(packet->payload));
                break;
            }
        } else {
            client->resendData(client->lastRR);
        }

    }

    client->sendHeader(ENDOFFILE);

    return NULL;
}
コード例 #12
0
ファイル: Client.cpp プロジェクト: chenbk85/ice
int
main(int argc, char* argv[])
{
#ifdef ICE_STATIC_LIBS
    Ice::registerIceSSL();
#endif

    Client app;

#ifndef _WIN32
    //
    // Switch to French locale
    // (we just used the codeset for as default internal code for
    // stringConverter below)
    //
    useLocale = (setlocale(LC_ALL, "fr_FR.ISO8859-15") != 0 || setlocale(LC_ALL, "fr_FR.iso885915@euro") != 0);
#endif

#if defined(_WIN32)
    //
    // 28605 == ISO 8859-15 codepage
    //
    IceUtil::setProcessStringConverter(new IceUtil::WindowsStringConverter(28605));
    useIconv = false;

#elif defined(__hpux)
    if(useLocale)
    {
        IceUtil::setProcessStringConverter(new IceUtil::IconvStringConverter<char>);
    }
    else
    {
        IceUtil::setProcessStringConverter(new IceUtil::IconvStringConverter<char>("iso815"));
    }
    IceUtil::setProcessWstringConverter(new IceUtil::IconvStringConverter<wchar_t>("ucs4"));
#else

    if(useLocale)
    {
        IceUtil::setProcessStringConverter(new IceUtil::IconvStringConverter<char>());
    }
    else
    {
        IceUtil::setProcessStringConverter(new IceUtil::IconvStringConverter<char>("ISO8859-15"));
    }

    if(sizeof(wchar_t) == 4)
    {
#  ifdef ICE_BIG_ENDIAN
        IceUtil::setProcessWstringConverter(new IceUtil::IconvStringConverter<wchar_t>("UTF-32BE"));
#  else
        IceUtil::setProcessWstringConverter(new IceUtil::IconvStringConverter<wchar_t>("UTF-32LE"));
#  endif
    }
    else
    {
#  ifdef ICE_BIG_ENDIAN
        IceUtil::setProcessWstringConverter(new IceUtil::IconvStringConverter<wchar_t>("UTF-16BE"));
#  else
        IceUtil::setProcessWstringConverter(new IceUtil::IconvStringConverter<wchar_t>("UTF-16LE"));
#  endif
    }
#endif
    return app.main(argc, argv);
}
コード例 #13
0
const QIconSet *Icons::getIcon(const char *name)
{
    if (name == NULL)
        return NULL;
    PIXMAP_MAP::iterator it = icons.find(name);
    if (it == icons.end()){
		string n = name;
        if (n == "online"){
            unsigned i;
			const QIconSet *icon = NULL;
			const char *icon_name = NULL;
            for (i = 0; i < getContacts()->nClients(); i++){
                Client *client = getContacts()->getClient(i);
				icon_name = client->protocol()->description()->icon;
                icon = Icon(icon_name);
                if (icon)
					break;
            }
			if (icon == NULL){
				icon_name = "ICQ";
				icon = Icon(icon_name);
			}
			if (icon == NULL)
				return NULL;
			unsigned flags = 0;
			it = icons.find(icon_name);
			if (it != icons.end())
				flags = (*it).second.flags;
			PictDef *d = addIcon(name, NULL, NULL, flags);
			d->iconSet = *icon;
			return icon;
        }
        if (n == "offline"){
            const QIconSet *icon = Icon("online");
            if (icon == NULL)
				return NULL;
			unsigned flags = 0;
			it = icons.find("online");
			if (it != icons.end())
				flags = (*it).second.flags;
			QIconSet offline = makeOffline(flags, icon);
			PictDef *d = addIcon(name, NULL, NULL, flags);
			d->iconSet = offline;
			return &d->iconSet;
        }
        if (n == "inactive"){
            const QIconSet *icon = Icon("online");
            if (icon == NULL)
				return NULL;
			unsigned flags = 0;
			it = icons.find("online");
			if (it != icons.end())
				flags = (*it).second.flags;
			QIconSet offline = makeInactive(icon);
			PictDef *d = addIcon(name, NULL, NULL, flags);
			d->iconSet = offline;
			return &d->iconSet;
        }
        if (n == "invisible"){
            const QIconSet *icon = Icon("online");
            if (icon == NULL)
				return NULL;
			unsigned flags = 0;
			it = icons.find("online");
			if (it != icons.end())
				flags = (*it).second.flags;
			QIconSet invisible = makeInvisible(flags, icon);
			PictDef *d = addIcon(name, NULL, NULL, flags);
			d->iconSet = invisible;
			return &d->iconSet;
        }
		int pos = n.find('_');
		if (pos > 0){
			const QIconSet *icon = Icon(n.substr(0, pos).c_str());
			unsigned flags = 0;
			it = icons.find(n.substr(0, pos).c_str());
			if (it != icons.end())
				flags = (*it).second.flags;
				QIconSet res;
			if (icon){
				string s = n.substr(pos + 1);
				if (s == "online"){
					res = *icon;
				}else if (s == "offline"){
					res = makeOffline(flags, icon);
				}else if (s == "invisible"){
					res = makeInvisible(flags, icon);
				}else{
					const QIconSet *i = Icon(s.c_str());
					if (i){
						res = mergeIcon(icon, i->pixmap(QIconSet::Small, QIconSet::Normal));
					}else{
					    it = icons.find(s.c_str());
						if (it != icons.end()){
							flags = (*it).second.flags;
							res = makeOffline(flags, icon);
						}
					}
				}
			}
			if (res.pixmap(QIconSet::Small, QIconSet::Normal).width()){
				PictDef *d = addIcon(name, NULL, NULL, flags);
				d->iconSet = res;
				return &d->iconSet;
			}
		}
		log(L_DEBUG, "Icon %s not found", name);
        return NULL;
    }
    PictDef &p = (*it).second;
	if (p.iconSet.pixmap(QIconSet::Small, QIconSet::Normal).width())
		return &p.iconSet;
#ifdef USE_KDE
    if (p.system){
        KIconLoader iconLoader;
        QPixmap pict = iconLoader.loadIcon(name, KIcon::Small, -22, KIcon::DefaultState, NULL, true);
		if (!pict.isNull()){
			QPixmap pict1 = iconLoader.loadIcon(name, KIcon::Desktop, -64, KIcon::DefaultState, NULL, true);
			if (pict.isNull()){
	            p.iconSet = QIconSet(pict);
			}else{
				p.iconSet = QIconSet(pict, pict1);
			}
			return &p.iconSet;
		}
    }
#endif
	QPixmap pict = loadPict(name);
	if (!pict.isNull()){
		if (pict.width() > 16){
			QImage img = pict.convertToImage();
			img = img.smoothScale(16, 16);
			QPixmap pict1(16, 16);
			pict1.convertFromImage(img);
			p.iconSet = QIconSet(pict1, pict);
		}else{
			p.iconSet = QIconSet(pict);
		}
		return &p.iconSet;
	}
	if (p.xpm){
		p.iconSet = QIconSet(QPixmap(p.xpm));
		return &p.iconSet;
	}
	log(L_DEBUG, "Icon %s is empty", name);
	return NULL;
}
コード例 #14
0
void Master::InitMS(ifstream &fin) //init the master, including the server chain and client chain
{
    char *input;
    string input_str;
    int flag_master = 0, flag_server = 0, flag_client = 0;
    while(fin.good())
    {
        getline(fin, input_str);
        if (input_str == "\0")
            continue;
        input = const_cast<char*>(input_str.c_str());
        if (!strncmp(input, "//Master", 8))
        {
            flag_master = 1;
            continue;
        }
        else if (!strncmp(input, "//Server", 8))
        {
            flag_server = 1;
            continue;
        }
        else if (!strncmp(input, "//Client ", 9))
        {
            flag_server = 0;
            continue;
        }
        else if (!strncmp(input, "//Client:", 9))
        {
            flag_client = 1;
            continue;
        }
        else if (!strncmp(input, "//Request", 9))
            break;
        if (flag_master)
        {
            Init(input_str);
            flag_master = 0;
            continue;
        }
        if (flag_server)
        {
            Server *s = new Server();
            s->InitServ(input_str);
            if (!s->Getdelay())
                Addserver(s);
        }
        if (flag_client)
        {
            Client *c = new Client();
            c->InitCli(input_str);
            Addclient(c);
        }
    }
    for(map<int, list<Server*> >::iterator it1 = sChain.begin(); it1 != sChain.end(); ++it1)
    {
        int count = 0;
        for(list<Server *>::iterator it2 = it1->second.begin(); it2 != it1->second.end(); ++it2,++count)
        {
            list<Server *>::iterator cur = it2;
            if(count == it1->second.size() - 1)
            {
                continue;
            }
            else
            {
                (*cur)->Setnext(*(++it2));
                
            }
            it2 = cur;
        }
    }
};
コード例 #15
0
ファイル: client.cpp プロジェクト: Inderjeet26/mongo
 string sayClientState() {
     Client* c = currentClient.get();
     if ( !c )
         return "no client";
     return c->toString();
 }
コード例 #16
0
bool MsgEdit::sendMessage(Message *msg)
{
    if (m_retry.msg){
        delete m_retry.msg;
        m_retry.msg = NULL;
    }
    if (m_msg){
        delete msg;
        if (EventMessageCancel(m_msg).process())
            m_msg = NULL;
        stopSend(false);
        return false;
    }
    bool bClose = true;
    if (CorePlugin::instance()->getContainerMode()){
        bClose = false;
        Command cmd;
        cmd->id		= CmdSendClose;
        cmd->param	= this;
        EventCommandWidget eWidget(cmd);
        eWidget.process();
        QToolButton *btnClose = qobject_cast<QToolButton*>(eWidget.widget());
        if (btnClose)
            bClose = btnClose->isChecked();
    }
    CorePlugin::instance()->setValue("CloseSend", bClose);

    Contact *contact = getContacts()->contact(m_userWnd->id());
    if (contact){
		SIM::PropertyHubPtr data = contact->getUserData("translit");
        if (!data.isNull() && data->value("Translit").toBool())
            msg->setFlags(msg->getFlags() | MESSAGE_TRANSLIT);
    }

    msg->setFlags(msg->getFlags() | m_flags);
    m_flags = 0;

    if (m_userWnd->m_list){
        if( !m_userWnd->m_list->isHaveSelected() )
            return false;
        multiply = m_userWnd->m_list->selected();
        msg->setContact( multiply.first() );
        multiply.pop_front();
        msg->setClient(NULL);
        if( multiply.count() > 0 )
            msg->setFlags(msg->getFlags() | MESSAGE_MULTIPLY);
    }else if (!m_resource.isEmpty()){
        void *data = NULL;
        Client *c = client(data, true, false, msg->contact(), true);
        if (c){
            QString resources = c->resources(data);
            while (!resources.isEmpty()){
                QString res = getToken(resources, ';');
                getToken(res, ',');
                if (m_resource == res){
                    msg->setResource(m_resource);
                    break;
                }
            }
        }
    }

    editLostFocus();
    Command cmd;
    cmd->id		= CmdSend;
    cmd->text	= I18N_NOOP("Cancel");
    cmd->icon	= "cancel";
    cmd->flags	= BTN_PICT;
    cmd->param	= this;
    EventCommandChange(cmd).process();
    m_msg = msg;
    return send();
}
コード例 #17
0
/* static */
void
Server :: receiveHandler(NetworkClient* aClient, uint8_t* aBuf, size_t aLen)
{
    if (aClient != nullptr && aBuf != nullptr)
    {
        if (aLen < sizeof(Msg::Header))
            return;

        uint8_t* received = new uint8_t[aLen];
        memcpy(received, aBuf, aLen);

        // TODO? clean this line and add some checks
        Client* client = (Client*)aClient->getOwner();
        client->getCipher().decrypt(received, aLen);

        size_t size = 0;
        for (size_t i = 0; i < aLen; i += size)
        {
            #if BYTE_ORDER == BIG_ENDIAN
            size = bswap16(((Msg::Header*)(received + i))->Length);
            #else
            size = ((Msg::Header*)(received + i))->Length;
            #endif

            ASSERT(size <= 1024); // invalid msg size...
            if (size < aLen)
            {
                uint8_t* packet = new uint8_t[size];
                memcpy(packet, received + i, size);

                #if BYTE_ORDER == BIG_ENDIAN
                Msg::Header* header = (Msg::Header*)packet;
                header->Length = bswap16(header->Length);
                header->Type = bswap16(header->Type);
                #endif

                Msg* msg = nullptr;
                Msg::create(&msg, &packet, size);
                msg->process(client);

                SAFE_DELETE(msg);
                SAFE_DELETE_ARRAY(packet);
            }
            else
            {
                #if BYTE_ORDER == BIG_ENDIAN
                Msg::Header* header = (Msg::Header*)received;
                header->Length = bswap16(header->Length);
                header->Type = bswap16(header->Type);
                #endif

                Msg* msg = nullptr;
                Msg::create(&msg, &received, size);
                msg->process(client);

                SAFE_DELETE(msg);
            }
        }

        SAFE_DELETE_ARRAY(received);
    }
}
コード例 #18
0
ファイル: Server.cpp プロジェクト: Chiranjivee/SFML-book
    void Server::runGame()
    {
        std::cout<<"Start Game service"<<std::endl;

        loadFromDb();
        while(!stop)
        {
            sf::Lock guard(_clientMutex);
            //for all clients
            for(auto it = _clients.begin(); it != _clients.end();++it)
            {
                Client* client = *it;
                packet::NetworkEvent* msg;
                while(client and client->pollEvent(msg))
                {
                    std::cout<<"Client "<<client->id()<<" recive data of type : "<<msg->type()<<std::endl;
                    switch(msg->type())
                    {
                        case FuncIds::IdGetListGame :
                        {
                            sf::Packet response;
                            packet::SetListGame list;
                            sf::Lock guard(_gameMutex);
                            for(auto game : _games)
                            {
                                list.add(game->id(),game->getPlayersCount(),game->getTeamCount());
                            }

                            response<<list;
                            client->send(response);
                        }break;
                        case FuncIds::IdCreateGame :
                        {
                            sf::Packet response;
                            packet::SetListGame list;
                            sf::Lock guard(_gameMutex);
                            _games.emplace_back(new Game("./media/map.json"));
                            _games.back()->load(true);

                            for(auto game : _games)
                            {
                                list.add(game->id(),game->getPlayersCount(),game->getTeamCount());
                            }
                            _games.back()->onLogOut = onLogOut;
                            _games.back()->run();

                            response<<list;
                            //send new game to all clients
                            for(auto it2 = _clients.begin(); it2 != _clients.end();++it2)
                                (*it2)->send(response);
                        }break;
                        case FuncIds::IdJoinGame :
                        {
                            int gameId = static_cast<packet::JoinGame*>(msg)->gameId();
                            sf::Lock guard(_gameMutex);
                            for(auto game : _games)
                            {
                                if(game->id() == gameId)
                                {
                                    if(game->addClient(client))
                                    {
                                        client = nullptr;
                                        it = _clients.erase(it);
                                        --it;
                                    }
                                    break;
                                }
                            }

                        }break;

                        case FuncIds::IdDisconnected :
                        {
                            it = _clients.erase(it);
                            --it;
                            client = nullptr;
                        }break;
                        default : break;
                    }
                    delete msg;
                }
            }
        }

        std::cout<<"Stop Game service"<<std::endl;
        {
            sf::Lock guard(_gameMutex);
            for(auto& game : _games)
            {
                std::cout<<"Stop Game "<<game->id()<<std::endl;
                game->stop();
                game->wait();
            }
            saveToDb();
        }
    }
コード例 #19
0
ファイル: range_deleter.cpp プロジェクト: megawac/mongo
void RangeDeleter::doWork() {
    Client::initThreadIfNotAlready("RangeDeleter");
    Client* client = &cc();

    while (!inShutdown() && !stopRequested()) {
        string errMsg;

        RangeDeleteEntry* nextTask = NULL;

        {
            stdx::unique_lock<stdx::mutex> sl(_queueMutex);
            while (_taskQueue.empty()) {
                _taskQueueNotEmptyCV.wait_for(sl,
                                              stdx::chrono::milliseconds(kNotEmptyTimeoutMillis));

                if (stopRequested()) {
                    log() << "stopping range deleter worker" << endl;
                    return;
                }

                if (_taskQueue.empty()) {
                    // Try to check if some deletes are ready and move them to the
                    // ready queue.

                    TaskList::iterator iter = _notReadyQueue.begin();
                    while (iter != _notReadyQueue.end()) {
                        RangeDeleteEntry* entry = *iter;

                        set<CursorId> cursorsNow;
                        if (entry->options.waitForOpenCursors) {
                            auto txn = client->makeOperationContext();
                            _env->getCursorIds(txn.get(), entry->options.range.ns, &cursorsNow);
                        }

                        set<CursorId> cursorsLeft;
                        std::set_intersection(entry->cursorsToWait.begin(),
                                              entry->cursorsToWait.end(),
                                              cursorsNow.begin(),
                                              cursorsNow.end(),
                                              std::inserter(cursorsLeft, cursorsLeft.end()));

                        entry->cursorsToWait.swap(cursorsLeft);

                        if (entry->cursorsToWait.empty()) {
                            (*iter)->stats.queueEndTS = jsTime();
                            _taskQueue.push_back(*iter);
                            _taskQueueNotEmptyCV.notify_one();
                            iter = _notReadyQueue.erase(iter);
                        } else {
                            logCursorsWaiting(entry);
                            ++iter;
                        }
                    }
                }
            }

            if (stopRequested()) {
                log() << "stopping range deleter worker" << endl;
                return;
            }

            nextTask = _taskQueue.front();
            _taskQueue.pop_front();

            _deletesInProgress++;
        }

        {
            auto txn = client->makeOperationContext();
            nextTask->stats.deleteStartTS = jsTime();
            bool delResult =
                _env->deleteRange(txn.get(), *nextTask, &nextTask->stats.deletedDocCount, &errMsg);
            nextTask->stats.deleteEndTS = jsTime();

            if (delResult) {
                nextTask->stats.waitForReplStartTS = jsTime();

                if (!_waitForMajority(txn.get(), &errMsg)) {
                    warning() << "Error encountered while waiting for replication: " << errMsg;
                }

                nextTask->stats.waitForReplEndTS = jsTime();
            } else {
                warning() << "Error encountered while trying to delete range: " << errMsg << endl;
            }
        }

        {
            stdx::lock_guard<stdx::mutex> sl(_queueMutex);

            NSMinMax setEntry(nextTask->options.range.ns,
                              nextTask->options.range.minKey,
                              nextTask->options.range.maxKey);
            deletePtrElement(&_deleteSet, &setEntry);
            _deletesInProgress--;

            if (nextTask->notifyDone) {
                nextTask->notifyDone->notifyOne();
            }
        }

        recordDelStats(new DeleteJobStats(nextTask->stats));
        delete nextTask;
        nextTask = NULL;
    }
}
コード例 #20
0
ファイル: Client.cpp プロジェクト: scott-nelson/fastbuild
// ThreadFuncStatic
//------------------------------------------------------------------------------
/*static*/ uint32_t Client::ThreadFuncStatic( void * param )
{
	Client * c = (Client *)param;
	c->ThreadFunc();
	return 0;
}
コード例 #21
0
ファイル: client.cpp プロジェクト: asdlei00/ACE
int
ACE_TMAIN(int argc, ACE_TCHAR *argv[])
{
  try
    {
      CORBA::ORB_var orb =
        CORBA::ORB_init (argc, argv);

      if (parse_args (argc, argv) != 0)
        return 1;

      A::AMI_Test_var server;

      CORBA::Object_var object =
        orb->string_to_object (ior);
      server =  A::AMI_Test::_narrow (object.in ());

      if (CORBA::is_nil (server.in ()))
        {
          ACE_ERROR_RETURN ((LM_ERROR,
                             "Object reference <%s> is nil.\n",
                             ior),
                            1);
        }

      // Activate POA to handle the call back.

      CORBA::Object_var poa_object =
        orb->resolve_initial_references("RootPOA");

      if (CORBA::is_nil (poa_object.in ()))
        ACE_ERROR_RETURN ((LM_ERROR,
                           " (%P|%t) Unable to initialize the POA.\n"),
                          1);

      PortableServer::POA_var root_poa =
        PortableServer::POA::_narrow (poa_object.in ());

      PortableServer::POAManager_var poa_manager =
        root_poa->the_POAManager ();

      poa_manager->activate ();

      // Let the client perform the test in a separate thread
      Handler handler;
      PortableServer::ObjectId_var id =
        root_poa->activate_object (&handler);

      CORBA::Object_var hnd_object = root_poa->id_to_reference (id.in ());

      A::AMI_AMI_TestHandler_var the_handler_var =
        A::AMI_AMI_TestHandler::_narrow (hnd_object.in ());

      handler.set_ami_test (server.in ());

      Client client (server.in (), niterations, the_handler_var.in ());
      if (client.activate (THR_NEW_LWP | THR_JOINABLE,
                           nthreads) != 0)
        ACE_ERROR_RETURN ((LM_ERROR,
                           "Cannot activate client threads\n"),
                          1);

      // Main thread collects replies. It needs to collect
      // <nthreads*niterations> replies.
      number_of_replies = nthreads *niterations;

      if (debug)
        {
          ACE_DEBUG ((LM_DEBUG,
                      "(%P|%t) : Entering perform_work loop to receive <%d> replies\n",
                      number_of_replies.value ()));
        }

      // ORB loop.

      Worker worker (orb.in ());
      if (worker.activate (THR_NEW_LWP | THR_JOINABLE,
                           nthreads) != 0)
        ACE_ERROR_RETURN ((LM_ERROR,
                           "Cannot activate client threads\n"),
                          1);

      worker.thr_mgr ()->wait ();

      if (debug)
        {
          ACE_DEBUG ((LM_DEBUG,
                      "(%P|%t) : Exited perform_work loop Received <%d> replies\n",
                      (nthreads*niterations) - number_of_replies.value ()));
        }

      client.thr_mgr ()->wait ();

      ACE_DEBUG ((LM_DEBUG, "threads finished\n"));

      server->shutdown ();

      root_poa->destroy (1,  // ethernalize objects
                         0  // wait for completion
                        );

      orb->destroy ();
    }
  catch (const CORBA::Exception& ex)
    {
      ex._tao_print_exception ("Caught exception:");
      return 1;
    }

  return parameter_corruption;
}
コード例 #22
0
ファイル: worldserver.cpp プロジェクト: N0ctrnl/VAServer
void WorldServer::ProcessMessage(uint16 opcode, EQ::Net::Packet &p)
{
	ServerPacket tpack(opcode, p);
	ServerPacket *pack = &tpack;

	Log(Logs::Detail, Logs::UCS_Server, "Received Opcode: %4X", opcode);

	switch (opcode)
	{
	case 0: {
		break;
	}
	case ServerOP_KeepAlive:
	{
		break;
	}
	case ServerOP_UCSMessage:
	{
		char *Buffer = (char *)pack->pBuffer;

		auto From = new char[strlen(Buffer) + 1];

		VARSTRUCT_DECODE_STRING(From, Buffer);

		std::string Message = Buffer;

		Log(Logs::Detail, Logs::UCS_Server, "Player: %s, Sent Message: %s", From, Message.c_str());

		Client *c = g_Clientlist->FindCharacter(From);

		safe_delete_array(From);

		if (Message.length() < 2)
			break;

		if (!c)
		{
			Log(Logs::Detail, Logs::UCS_Server, "Client not found.");
			break;
		}

		if (Message[0] == ';')
		{
			std::string new_message;
			switch (c->GetClientVersion()) {
			case EQEmu::versions::ClientVersion::Titanium:
				Client45ToServerSayLink(new_message, Message.substr(1, std::string::npos));
				break;
			case EQEmu::versions::ClientVersion::SoF:
			case EQEmu::versions::ClientVersion::SoD:
			case EQEmu::versions::ClientVersion::UF:
				Client50ToServerSayLink(new_message, Message.substr(1, std::string::npos));
				break;
			case EQEmu::versions::ClientVersion::RoF:
				Client55ToServerSayLink(new_message, Message.substr(1, std::string::npos));
				break;
			case EQEmu::versions::ClientVersion::RoF2:
			default:
				new_message = Message.substr(1, std::string::npos);
				break;
			}

			c->SendChannelMessageByNumber(new_message);
		}
		else if (Message[0] == '[')
		{
			g_Clientlist->ProcessOPMailCommand(c, Message.substr(1, std::string::npos));
		}

		break;
	}

	case ServerOP_UCSMailMessage:
	{
		ServerMailMessageHeader_Struct *mail = (ServerMailMessageHeader_Struct*)pack->pBuffer;
		database.SendMail(std::string("SOE.EQ.") + Config->ShortName + std::string(".") + std::string(mail->to),
			std::string(mail->from),
			mail->subject,
			mail->message,
			std::string());
		break;
	}
	}
}
コード例 #23
0
void SearchDialog::fillClients()
{
    vector<ClientWidget> widgets = m_widgets;
    m_widgets.clear();
    m_search->cmbClients->clear();
    unsigned nClients = 0;
    int current    = -1;
    int defCurrent = -1;
    for (unsigned i = 0; i < getContacts()->nClients(); i++){
        Client *client = getContacts()->getClient(i);
        QWidget *search = client->searchWindow(m_search->wndCondition);
        if (search == NULL)
            continue;
        unsigned n;
        for (n = 0; n < widgets.size(); n++){
            if ((widgets[n].client != client) || !widgets[n].name.isEmpty())
                continue;
            delete search;
            search = widgets[n].widget;
            widgets[n].widget = NULL;
            break;
        }
        if (n >= widgets.size())
            m_id = m_search->wndCondition->addWidget(search);
        m_search->cmbClients->addItem(Icon(client->protocol()->description()->icon),
                                      CorePlugin::instance()->clientName(client));
        ClientWidget cw;
        cw.client = client;
        cw.widget = search;
        m_widgets.push_back(cw);
        if (search == m_current)
            current = m_widgets.size() - 1;
        if (client->protocol()->description()->flags & PROTOCOL_SEARCH)
            nClients++;
        if (client->name() == CorePlugin::instance()->value("SearchClient").toString())
            defCurrent = m_widgets.size() - 1;
    }


    if (nClients > 1){
        unsigned n;
        QWidget *search = NULL;
        for (n = 0; n < widgets.size(); n++){
            if (widgets[n].client == (Client*)(-1)){
                search = widgets[n].widget;
                widgets[n].widget = NULL;
                break;
            }
        }
        if (search == NULL){
            search = new SearchAll(NULL);
            m_id = m_search->wndCondition->addWidget(search);
        }
        m_search->cmbClients->addItem(Icon("find"), i18n("All networks"));
        ClientWidget cw;
        cw.client = (Client*)(-1);
        cw.widget = search;
        m_widgets.push_back(cw);
        if ((search == m_current) || ((m_current == NULL) && (current < 0) && (defCurrent < 0)))
            current = m_widgets.size() - 1;
    }
    unsigned n;
    QWidget *search = NULL;
    for (n = 0; n < widgets.size(); n++){
        if (widgets[n].client == NULL){
            search = widgets[n].widget;
            widgets[n].widget = NULL;
            break;
        }
    }
    if (search == NULL){
        search = new NonIM(NULL);
        m_id = m_search->wndCondition->addWidget(search);
    }
    m_search->cmbClients->addItem(Icon("nonim"), i18n("Non-IM contact"));
    ClientWidget cw;
    cw.client = NULL;
    cw.widget = search;
    m_widgets.push_back(cw);
    if (search == m_current)
        current = m_widgets.size() - 1;

    if (m_update->isActive()){
        m_update->stop();
    }else if (m_result){
        m_result->viewport()->setUpdatesEnabled(false);
    }
    for (n = 0; n < widgets.size(); n++){
        if (widgets[n].name.isEmpty())
            continue;
        unsigned i;
        for (i = 0; i < m_widgets.size(); i++)
            if (widgets[n].client == m_widgets[i].client)
                break;
        if (i >= m_widgets.size())
            continue;
        m_search->cmbClients->addItem(Icon(widgets[n].client->protocol()->description()->icon),
                                      widgets[n].name);
        m_widgets.push_back(widgets[n]);
        widgets[n].widget = NULL;
    }
    for (n = 0; n < widgets.size(); n++){
        if (widgets[n].widget){
            if (widgets[n].widget == m_active)
                searchDone(m_active);
            if (widgets[n].widget == m_current)
                m_current = NULL;
            for (int i = 0; i < m_result->topLevelItemCount(); i++){
                QTreeWidgetItem *item = static_cast<QTreeWidgetItem*>(m_result->topLevelItem(i));
                if ((QWidget*)(item->text(COL_SEARCH_WND).toULong()) == widgets[n].widget)
                    delete item;
            }
            delete widgets[n].widget;
        }
    }

    if (current == -1)
        current = defCurrent;
    if (current == -1)
        current = 0;
    m_search->cmbClients->setCurrentIndex(current);
    clientActivated(current);
    setStatus();
    m_update->start(500);
}
コード例 #24
0
QString MsgViewBase::messageText(Message *msg)
{
    QString color;
    unsigned long c_sender   = (CorePlugin::m_plugin->getColorSender())  & 0xFFFFFF;
    unsigned long c_receiver = (CorePlugin::m_plugin->getColorReceiver())& 0xFFFFFF;
    unsigned long c_send     = 0x000000;
    unsigned long c_receive  = 0x000000;
    if (CorePlugin::m_plugin->getOwnColors()) {
        c_send     = (CorePlugin::m_plugin->getColorSend())    & 0xFFFFFF;
        c_receive  = (CorePlugin::m_plugin->getColorReceive()) & 0xFFFFFF;
    }
    color.sprintf(COLOR_FORMAT,
                  ((msg->getFlags() & MESSAGE_RECEIVED) ? c_receiver : c_sender));
    const char *icon = "message";
    const CommandDef *def = CorePlugin::m_plugin->messageTypes.find(msg->type());
    if (def)
        icon = def->icon;
    QString contactName;
    Client *client = NULL;
    Contact *contact = getContacts()->contact(msg->contact());
    if (contact){
        ClientDataIterator it(contact->clientData);
        void *data;
        while ((data = ++it) != NULL){
            if (it.client()->dataName(data) == msg->client()){
                client = it.client();
                break;
            }
        }
    }
    if (msg->type() == MessageStatus){
        icon = "empty";
        StatusMessage *sm = static_cast<StatusMessage*>(msg);
        if (client == NULL)
            client = getContacts()->getClient(0);
        if (client){
            for (def = client->protocol()->statusList(); def->text; def++){
                if (def->id == sm->getStatus()){
                    icon = def->icon;
                    break;
                }
            }
        }
    }
    bool bUnread = false;
    if (msg->getFlags() & MESSAGE_RECEIVED){
        if (contact)
            contactName = contact->getName();
        for (list<msg_id>::iterator it = CorePlugin::m_plugin->unread.begin(); it != CorePlugin::m_plugin->unread.end(); ++it){
            msg_id &m = (*it);
            if ((m.id == msg->id()) &&
                    (m.contact == msg->contact()) &&
                    (m.client == msg->client())){
                bUnread = true;
                break;
            }
        }
    }else{
        if (client)
            contactName = client->ownerName();
        if (contactName.isEmpty())
            contactName = getContacts()->owner()->getName();
    }
    if (contactName.isEmpty())
        contactName = "???";
    QString id = QString::number(msg->id());
    id += ",";
    if (msg->getBackground() != msg->getForeground())
        id += QString::number(msg->getBackground() & 0xFFFFFF);
    string client_str;
    if (msg->client())
        client_str = msg->client();
    if (!client_str.empty()){
        id += ",";
        id += quoteText(client_str.c_str());
    }
    QString icons;
    if (msg->getFlags() & MESSAGE_SECURE)
        icons += "<img src=\"icon:encrypted\">";
    if (msg->getFlags() & MESSAGE_URGENT)
        icons += "<img src=\"icon:urgentmsg\">";
    if (msg->getFlags() & MESSAGE_LIST)
        icons += "<img src=\"icon:listmsg\">";

    QString s = QString("<p><nobr>"
                        "<a href=\"msg://%1\"><img src=\"icon:%2\"></a>%3"
                        "&nbsp;%4<span style=\"color:#%5\">%6</span> &nbsp;"
                        "<font size=\"-1\">%7</font>%8"
                        "</nobr></p>")
                .arg(id)
                .arg(icon)
                .arg(icons)
                .arg(bUnread ? "<b>" : "")
                .arg(color)
                .arg(quoteString(contactName))
                .arg(formatTime(msg->getTime()))
                .arg(bUnread ? "</b>" : "");
    if (msg->type() != MessageStatus){
        QString msgText = msg->presentation();
        if (msgText.isEmpty()){
            unsigned type = msg->type();
            for (;;){
                CommandDef *cmd = CorePlugin::m_plugin->messageTypes.find(type);
                if (cmd == NULL)
                    break;
                MessageDef *def = (MessageDef*)(cmd->param);
                if (def->base_type){
                    type = def->base_type;
                    continue;
                }
                msgText += "<p>";
                msgText += i18n(def->singular, def->plural, 1);
                msgText += "</p>";
                break;
            }
            QString text = msg->getRichText();
            msgText += text;
        }
        Event e(EventEncodeText, &msgText);
        e.process();
        msgText = parseText(msgText, CorePlugin::m_plugin->getOwnColors(), CorePlugin::m_plugin->getUseSmiles());
        if (CorePlugin::m_plugin->getOwnColors()){
            color.sprintf(COLOR_FORMAT,
                          ((msg->getFlags() & MESSAGE_RECEIVED) ? c_receive : c_send));
            s += "<span style=\"color:#";
            s += color;
            s += "\">";
        }
        s += msgText;
        if (CorePlugin::m_plugin->getOwnColors())
            s += "</span>";
    }
    return s;
}
コード例 #25
0
/**
 * @brief survivalsquare::Chat
 */
void survivalsquare::Chat()
{
    Client * c = new Client();
    c->show();
}
コード例 #26
0
void ConfigureDialog::fill(unsigned id)
{
    lstBox->clear();
    lstBox->setSorting(1);

    ConfigItem *parentItem = new MainInfoItem(lstBox, 0);
    for (unsigned i = 0; i < getContacts()->nClients(); i++){
        Client *client = getContacts()->getClient(i);
        CommandDef *cmds = client->configWindows();
        if (cmds){
            parentItem = NULL;
            for (; cmds->text; cmds++){
                if (parentItem){
                    new ClientItem(parentItem, client, cmds);
                }else{
                    parentItem = new ClientItem(lstBox, client, cmds);
                    parentItem->setOpen(true);
                }
            }
        }
    }

    unsigned n;
    parentItem = NULL;
    list<unsigned> st;
    for (n = 0; n < getContacts()->nClients(); n++){
        Protocol *protocol = getContacts()->getClient(n)->protocol();
        if ((protocol->description()->flags & (PROTOCOL_AR | PROTOCOL_AR_USER)) == 0)
            continue;
        if (parentItem == NULL){
            parentItem = new ConfigItem(lstBox, 0);
            parentItem->setText(0, i18n("Autoreply"));
            parentItem->setOpen(true);
        }
        for (const CommandDef *d = protocol->statusList(); d->text; d++){
            if (((protocol->description()->flags & PROTOCOL_AR_OFFLINE) == 0) &&
                    ((d->id == STATUS_ONLINE) || (d->id == STATUS_OFFLINE)))
                continue;
            list<unsigned>::iterator it;
            for (it = st.begin(); it != st.end(); ++it)
                if ((*it) == d->id)
                    break;
            if (it != st.end())
                continue;
            st.push_back(d->id);
            new ARItem(parentItem, d);
        }
    }

    parentItem = new ConfigItem(lstBox, 0);
    parentItem->setText(0, i18n("Plugins"));
    parentItem->setPixmap(0, Pict("run", lstBox->colorGroup().base()));
    parentItem->setOpen(true);

    for ( n = 0;; n++){
        Event e(EventPluginGetInfo, (void*)n);
        pluginInfo *info = (pluginInfo*)e.process();
        if (info == NULL) break;
        if (info->info == NULL){
            Event e(EventLoadPlugin, (char*)info->name.c_str());
            e.process();
        }
        if ((info->info == NULL) || (info->info->title == NULL)) continue;
        QString title = i18n(info->info->title);
        new PluginItem(parentItem, title, info, n);
    }

    QFontMetrics fm(lstBox->font());
    unsigned w = 0;
    for (QListViewItem *item = lstBox->firstChild(); item; item = item->nextSibling()){
        w = QMAX(w, itemWidth(item, fm));
    }
    lstBox->setFixedWidth(w);
    lstBox->setColumnWidth(0, w - 2);

    if (id){
        for (QListViewItem *item = lstBox->firstChild(); item; item = item->nextSibling()){
            if (setCurrentItem(item, id))
                return;
        }
    }
    lstBox->setCurrentItem(lstBox->firstChild());
}
コード例 #27
0
ファイル: db.cpp プロジェクト: kevleyski/mongo
 virtual void disconnected( AbstractMessagingPort* p ) {
     Client * c = currentClient.get();
     if( c ) c->shutdown();
 }
コード例 #28
0
ファイル: guild_process.cpp プロジェクト: cavedude00/eqmacemu
void Client::GuildCommand(Seperator* sep)
{
		zgm.LoadGuilds();
		Guild_Struct* guilds = zgm.GetGuildList();


	if (strcasecmp(sep->arg[1], "help") == 0)
	{
		this->GuildPCCommandHelp();
		this->GuildGMCommandHelp();
	}
	else if (strcasecmp(sep->arg[1], "status") == 0 || strcasecmp(sep->arg[1], "stat") == 0)
	{
		Client* client = 0;

		if (sep->arg[2][0] != 0)
		{
			client = entity_list.GetClientByName(sep->argplus[2]);
		}
		else if (target != 0 && target->IsClient())
		{
			client = target->CastToClient();
		}

		if (client == 0)
		{
			this->Message(BLACK, "You must target someone or specify a character name");
		}
		else if ((client->Admin() >= 100 && admin < 100) && client->GuildDBID() != guilddbid) // no peeping for GMs, make sure tell message stays the same
		{
			this->Message(BLACK, "You must target someone or specify a character name.");
		}
		else 
		{
			if (client->GuildDBID() == 0)
			{
				this->Message(BLACK, "%s is not in a guild.", client->GetName());
			}
			else if (guilds[client->GuildEQID()].leader == client->AccountID())
			{
				this->Message(BLACK, "%s is the leader of <%s> rank: %s", client->GetName(), guilds[client->GuildEQID()].name, guilds[client->GuildEQID()].rank[client->GuildRank()].rankname);
			}
			else
			{
				this->Message(BLACK, "%s is a member of <%s> rank: %s", client->GetName(), guilds[client->GuildEQID()].name, guilds[client->GuildEQID()].rank[client->GuildRank()].rankname);
			}
		}
	}
	else if (strcasecmp(sep->arg[1], "info") == 0)
	{
		if (sep->arg[2][0] == 0 && guilddbid == 0)
		{
			if (admin >= 100)
			{
				this->Message(BLACK, "Usage: #guildinfo guilddbid");
			}
			else
			{
				this->Message(BLACK, "You're not in a guild");
			}
		}
		else
		{
			int32 tmp;
		
			if (sep->arg[2][0] == 0)
			{
				tmp = Database::Instance()->GetGuildEQID(guilddbid);
			}
			else
			{
				tmp = Database::Instance()->GetGuildEQID(atoi(sep->arg[2]));
			}

			if (tmp < 0 || tmp >= 512)
			{
				this->Message(BLACK, "Guild not found.");
			}
			else
			{
				this->Message(BLACK, "Guild info DB# %i, %s", guilds[tmp].databaseID, guilds[tmp].name);
			
				if (this->admin >= 100 || guildeqid == tmp)
				{
					if (this->account_id == guilds[tmp].leader || guildrank == 0 || admin >= 100)
					{
						char leadername[32];
						Database::Instance()->GetAccountName(guilds[tmp].leader, leadername);
						this->Message(BLACK, "Guild Leader: %s", leadername);
					}

					for (int i = 0; i <= GUILD_MAX_RANK; i++)
					{
						this->Message(BLACK, "Rank %i: %s", i, guilds[tmp].rank[i].rankname);
						this->Message(BLACK, "  HearGU: %i  SpeakGU: %i  Invite: %i  Remove: %i  Promote: %i  Demote: %i  MOTD: %i  War/Peace: %i", guilds[tmp].rank[i].heargu, guilds[tmp].rank[i].speakgu, guilds[tmp].rank[i].invite, guilds[tmp].rank[i].remove, guilds[tmp].rank[i].promote, guilds[tmp].rank[i].demote, guilds[tmp].rank[i].motd, guilds[tmp].rank[i].warpeace);
					}
				}
			}
		}
	}
	else if (strcasecmp(sep->arg[1], "leader") == 0) 
	{
		if (guilddbid == 0)
		{
			this->Message(BLACK, "You arent in a guild!");
		}
		else if (guilds[guildeqid].leader != account_id)
		{
			this->Message(BLACK, "You aren't the guild leader.");
		}
		else
		{
			char* tmptar = 0;

			if (sep->arg[2][0] != 0)
			{
				tmptar = sep->argplus[2];
			}
			else if (tmptar == 0 && target != 0 && target->IsClient())
			{
				tmptar = target->CastToClient()->GetName();
			}
			
			if (tmptar == 0)
			{
				Message(BLACK, "You must target someone or specify a character name.");
			}
			else
			{
				// Dark-Prince - 10/05/2008 - Code Consolidation
				//zgm.InviteToGuild(
				//this->SendGuildInvitePacket(tmptar);
			}
		}
	}
	else if (strcasecmp(sep->arg[1], "invite") == 0)
	{
		int32 GuildDBID = atoi(sep->arg[2]);
		Client* Invitee = entity_list.GetClientByName(sep->arg[3]);
		GUILDRANK Rank = (GUILDRANK)atoi(sep->arg[4]);

		int32 GuidlEQID = Database::Instance()->GetGuildEQID(GuildDBID);

		zgm.InviteToGuild(GuildDBID, GuidlEQID, this, Invitee, Rank);
	}
	else if (strcasecmp(sep->arg[1], "remove") == 0)
	{
		Client* Removee = entity_list.GetClientByName(sep->arg[2]);

		if(Removee != 0)
		{
			zgm.RemovePCFromGuild(this, Removee);
		}
	}
	else if (strcasecmp(sep->arg[1], "promote") == 0)
	{
		if (guilddbid == 0)
		{
			Message(BLACK, "You arent in a guild!");
		}
		else if (!(strlen(sep->arg[2]) == 1 && sep->arg[2][0] >= '0' && sep->arg[2][0] <= '9'))
		{
			Message(BLACK, "Usage: #guild promote rank [charname]");
		}
		else if (atoi(sep->arg[2]) < 0 || atoi(sep->arg[2]) > GUILD_MAX_RANK)
		{
			Message(BLACK, "Error: invalid rank #.");
		}
		else
		{
			char* tmptar = 0;

			if (sep->arg[3][0] != 0)
			{
				tmptar = sep->argplus[3];
			}
			else if (tmptar == 0 && target != 0 && target->IsClient())
			{
				tmptar = target->CastToClient()->GetName();
			}

			if (tmptar == 0)
			{
				Message(BLACK, "You must target someone or specify a character name.");
			}
			else
			{
				zgm.SendGuildPromotePacket(tmptar, this->GetName());
			}
		}
	}
	else if (strcasecmp(sep->arg[1], "demote") == 0)
	{
		if (guilddbid == 0)
		{
			Message(BLACK, "You arent in a guild!");
		}
		else if (!(strlen(sep->arg[2]) == 1 && sep->arg[2][0] >= '0' && sep->arg[2][0] <= '9'))
		{
			Message(BLACK, "Usage: #guild demote rank [charname]");
		}
		else if (atoi(sep->arg[2]) < 0 || atoi(sep->arg[2]) > GUILD_MAX_RANK)
		{
			Message(BLACK, "Error: invalid rank #.");
		}
		else 
		{
			char* tmptar = 0;
			if (sep->arg[3][0] != 0)
			{
				tmptar = sep->argplus[3];
			}
			else if (tmptar == 0 && target != 0 && target->IsClient())
			{
				tmptar = target->CastToClient()->GetName();
			}
			if (tmptar == 0)
			{
				Message(BLACK, "You must target someone or specify a character name.");
			}
			else
			{
				zgm.SendGuildDemotePacket(tmptar);
			}
		}
	}
	else if (strcasecmp(sep->arg[1], "motd") == 0)
	{
		if (guilddbid == 0)
		{
			Message(BLACK, "You arent in a guild!");
		}
		else if (!guilds[guildeqid].rank[guildrank].motd)
		{
			Message(BLACK, "You dont have permission to change the motd.");
		}
		else if (!worldserver.Connected())
		{
			Message(BLACK, "Error: World server dirconnected");
		}
		else
		{
			char tmp[255];

			if (strcasecmp(sep->argplus[2], "none") == 0)
			{
				strcpy(tmp, "");
			}
			else
			{
				snprintf(tmp, sizeof(tmp), "%s - %s", this->GetName(), sep->argplus[2]);
			}

			if (Database::Instance()->SetGuildMOTD(guilddbid, tmp))
			{
				// Dark-Prince - 10/05/2008 - Code Consolidation
/*
				ServerPacket* pack = new ServerPacket;
				pack->opcode = ServerOP_RefreshGuild;
				pack->size = 5;
				pack->pBuffer = new uchar[pack->size];
				memcpy(pack->pBuffer, &guildeqid, 4);
				worldserver.SendPacket(pack);
				safe_delete(pack);//delete pack;
*/
			}
			else
			{
				this->Message(BLACK, "Motd update failed.");
			}
		}
	}
	else if (strcasecmp(sep->arg[1], "edit") == 0)
	{
		if (guilddbid == 0)
		{
			Message(BLACK, "You arent in a guild!");
		}
		else if (!sep->IsNumber(2))
		{
			Message(BLACK, "Error: invalid rank #.");
		}
		else if (atoi(sep->arg[2]) < 0 || atoi(sep->arg[2]) > GUILD_MAX_RANK)
		{
			Message(BLACK, "Error: invalid rank #.");
		}
		else if (!guildrank == 0)
		{
			Message(BLACK, "You must be rank %s to use edit.", guilds[guildeqid].rank[0].rankname);
		}
		else if (!worldserver.Connected())
		{
			Message(BLACK, "Error: World server dirconnected");
		}
		else
		{
			if (!GuildEditCommand(guilddbid, guildeqid, atoi(sep->arg[2]), sep->arg[3], sep->argplus[4]))
			{
				Message(BLACK, "  #guild edit rank title newtitle");
				Message(BLACK, "  #guild edit rank permission 0/1");
			}
			else
			{
				zgm.SendGuildRefreshPacket(guildeqid);
			}
		}
	}
	// Start of GM Guild Commands
	else if (strcasecmp(sep->arg[1], "gmedit") == 0 && admin >= 100) 
	{
		if (!sep->IsNumber(2))
		{
			Message(BLACK, "Error: invalid guilddbid.");
		}
		else if (!sep->IsNumber(3))
		{
			Message(BLACK, "Error: invalid rank #.");
		}
		else if (atoi(sep->arg[3]) < 0 || atoi(sep->arg[3]) > GUILD_MAX_RANK)
		{
			Message(BLACK, "Error: invalid rank #.");
		}
		else if (!worldserver.Connected())
		{
			Message(BLACK, "Error: World server dirconnected");
		}
		else 
		{
			int32 eqid = Database::Instance()->GetGuildEQID(atoi(sep->arg[2]));
			
			if (eqid == 0xFFFFFFFF)
			{
				Message(BLACK, "Error: Guild not found");
			}
			else if (!GuildEditCommand(atoi(sep->arg[2]), eqid, atoi(sep->arg[3]), sep->arg[4], sep->argplus[5]))
			{
				Message(BLACK, "  #guild gmedit guilddbid rank title newtitle");
				Message(BLACK, "  #guild gmedit guilddbid rank permission 0/1");
			}
			else
			{
				zgm.SendGuildRefreshPacket(eqid);
			}
		}
	}
	else if (strcasecmp(sep->arg[1], "set") == 0 && admin >= 100)
	{
		if (!sep->IsNumber(3))
		{
			Message(BLACK, "Usage: #guild set charname guildgbid (0 = clear guildtag)");
		}
		else
		{
			/* -- Work in progress
			GUILDRANK rank = GuildMember;

			Client* c = entity_list.GetClientByName(sep->arg[2]);

			if(c == 0)
			{
				Message(BLACK, "Player not found!");
				return;
			}

			int GuidDBID = atoi(sep->arg[3]);

			if(sep->IsNumber(4))
			{
				rank = (GUILDRANK)atoi(sep->arg[4]);
			}
			
			zgm.LoadGuilds();

			
			int32 GuidEQID = Database::Instance()->GetGuildEQID(GuidDBID);
			zgm.InviteToGuild(GuidDBID, GuidEQID, this, c, rank);
			*/
			
			ServerPacket* pack = new ServerPacket(ServerOP_GuildGMSet, sizeof(ServerGuildCommand_Struct));
			pack->pBuffer = new uchar[pack->size];
			memset(pack->pBuffer, 0, pack->size);
			ServerGuildCommand_Struct* sgc = (ServerGuildCommand_Struct*) pack->pBuffer;
			sgc->guilddbid = atoi(sep->arg[3]);
			sgc->admin = admin;
			strcpy(sgc->from, name);
			strcpy(sgc->target, sep->arg[2]);
			worldserver.SendPacket(pack);
			safe_delete(pack);//delete pack;
		}
	}
	else if (strcasecmp(sep->arg[1], "setrank") == 0 && admin >= 100)
	{
		if (!sep->IsNumber(3))
		{
			Message(BLACK, "Usage: #guild setrank charname rank");
		}
		else if (atoi(sep->arg[3]) < 0 || atoi(sep->arg[3]) > GUILD_MAX_RANK)
		{
			Message(BLACK, "Error: invalid rank #.");
		}
		else
		{
			ServerPacket* pack = new ServerPacket(ServerOP_GuildGMSetRank, sizeof(ServerGuildCommand_Struct));


			pack->pBuffer = new uchar[pack->size];
			memset(pack->pBuffer, 0, pack->size);
			ServerGuildCommand_Struct* sgc = (ServerGuildCommand_Struct*) pack->pBuffer;
			sgc->newrank = (GUILDRANK)atoi(sep->arg[3]);
			sgc->admin = admin;
			strcpy(sgc->from, name);
			strcpy(sgc->target, sep->arg[2]);
			worldserver.SendPacket(pack);
			

			target->CastToClient()->SetGuild(target->CastToClient()->guilddbid, sgc->newrank);

			safe_delete(pack);//delete pack;
		}
	}
	/* New Guild Creation -> Challenge/Response method */
	else if (strcasecmp(sep->arg[1], "dpcreate") == 0 && admin >= 100)
	{
		if (sep->arg[3][0] == 0)
		{
			Message(BLACK, "Usage: #guild create {guildleader charname or AccountID} guild name");
		}
		else if (!worldserver.Connected())
		{
			Message(BLACK, "Error: World server dirconnected");
		}
		else
		{
			zgm.CreateGuildRequest(this, sep->arg[2], sep->argplus[3]);
		}
	}
	/* END New Guild Creation -> Challenge/Response method */
	else if (strcasecmp(sep->arg[1], "create") == 0 && admin >= 100)
	{
		if (sep->arg[3][0] == 0)
		{
			Message(BLACK, "Usage: #guild create {guildleader charname or AccountID} guild name");
		}
		else if (!worldserver.Connected())
		{
			Message(BLACK, "Error: World server dirconnected");
		}
		else
		{
			Client* Leader = entity_list.GetClientByName(sep->arg[2]);

			int32 guilddbid = 0;

			if(Leader != 0)
			{
				zgm.CreateGuild(this, Leader, sep->argplus[3], guilddbid);
			}			
		}
	}
	else if (strcasecmp(sep->arg[1], "delete") == 0 && admin >= 100)
	{
		if (!sep->IsNumber(2))
		{
			Message(BLACK, "Usage: #guild delete guildDBID");
		}
		else if (!worldserver.Connected())
		{
			Message(BLACK, "Error: World server dirconnected");
		}
		else
		{
			int32 tmpeq = Database::Instance()->GetGuildEQID(atoi(sep->arg[2]));
			char tmpname[32];

			if (tmpeq != 0xFFFFFFFF)
			{
				strcpy(tmpname, guilds[tmpeq].name);
			}

			if (!Database::Instance()->DeleteGuild(atoi(sep->arg[2])))
			{
				Message(BLACK, "Guild delete failed.");
			}
			else
			{
				if (tmpeq != 0xFFFFFFFF)
				{
					zgm.LoadGuilds();

					ServerPacket* pack = new ServerPacket(ServerOP_RefreshGuild, 5);
					
					pack->pBuffer = new uchar[pack->size];
					memcpy(pack->pBuffer, &tmpeq, 4);
					pack->pBuffer[4] = 1;
					worldserver.SendPacket(pack);
					safe_delete(pack);//delete pack;

					Message(BLACK, "Guild deleted: DB# %i, EQ# %i: %s", atoi(sep->arg[2]), tmpeq, tmpname);
				} 
				else
				{
					Message(BLACK, "Guild deleted: DB# %i", atoi(sep->arg[2]));
				}
			}
		}
	}
	else if (strcasecmp(sep->arg[1], "rename") == 0 && admin >= 100)
	{
		if ((!sep->IsNumber(2)) || sep->arg[3][0] == 0)
		{
			Message(BLACK, "Usage: #guild rename guildDBID newname");
		}
		else if (!worldserver.Connected())
		{
			Message(BLACK, "Error: World server dirconnected");
		}
		else
		{
			int32 tmpeq = Database::Instance()->GetGuildEQID(atoi(sep->arg[2]));
			char tmpname[32];

			if (tmpeq != 0xFFFFFFFF)
			{
				strcpy(tmpname, guilds[tmpeq].name);
			}

			if (!Database::Instance()->RenameGuild(atoi(sep->arg[2]), sep->argplus[3]))
			{
				Message(BLACK, "Guild rename failed.");
			}
			else 
			{
				if (tmpeq != 0xFFFFFFFF) 
				{
					ServerPacket* pack = new ServerPacket(ServerOP_RefreshGuild, 5);
					pack->pBuffer = new uchar[pack->size];
					memcpy(pack->pBuffer, &tmpeq, 4);
					pack->pBuffer[4] = 1;
					worldserver.SendPacket(pack);
					safe_delete(pack);//delete pack;

					Message(BLACK, "Guild renamed: DB# %i, EQ# %i, OldName: %s, NewName: %s", atoi(sep->arg[2]), tmpeq, tmpname, sep->argplus[3]);
				}
				else
				{
					Message(BLACK, "Guild renamed: DB# %i, NewName: %s", atoi(sep->arg[2]), sep->argplus[3]);
				}
			}
		}
	}
	else if (strcasecmp(sep->arg[1], "setleader") == 0 && admin >= 100) 
	{
		if (sep->arg[3][0] == 0 || !sep->IsNumber(2))
		{
			Message(BLACK, "Usage: #guild setleader guilddbid {guildleader charname or AccountID}");
		}
		else if (!worldserver.Connected())
		{
			Message(BLACK, "Error: World server dirconnected");
		}
		else
		{
			int32 leader = 0;
			
			if (sep->IsNumber(3))
			{
				leader = atoi(sep->arg[3]);
			}
			else
			{
				leader = Database::Instance()->GetAccountIDByChar(sep->argplus[3]);
			}

			int32 tmpdb = Database::Instance()->GetGuildDBIDbyLeader(leader);
			
			if (leader == 0)
			{
				Message(BLACK, "New leader not found.");
			}
			else if (tmpdb != 0) 
			{
				int32 tmpeq = Database::Instance()->GetGuildEQID(tmpdb);

				if (tmpeq >= 512)
				{
					Message(BLACK, "Error: %s already is the leader of DB# %i.", sep->argplus[3], tmpdb);
				}
				else
				{
					Message(BLACK, "Error: %s already is the leader of DB# %i <%s>.", sep->argplus[3], tmpdb, guilds[tmpeq].name);
				}
			}
			else 
			{
				int32 tmpeq = Database::Instance()->GetGuildEQID(atoi(sep->arg[2]));

				if (tmpeq == 0xFFFFFFFF)
				{
					Message(BLACK, "Guild not found.");
				}
				else if (!Database::Instance()->SetGuildLeader(atoi(sep->arg[2]), leader))
				{
					Message(BLACK, "Guild leader change failed.");
				}
				else
				{
					zgm.SendGuildRefreshPacket(tmpeq);

					Message(BLACK, "Guild leader changed: DB# %s, Leader: %s, Name: <%s>", sep->arg[2], sep->argplus[3], guilds[tmpeq].name);
				}
			}
		}
	}
	else if (strcasecmp(sep->arg[1], "list") == 0 && admin >= 100)
	{
		int x = 0;
		Message(BLACK, "Listing guilds on the server:");
		char leadername[32];
		int magicnumber = 512;

		zgm.LoadGuilds();
		guilds = zgm.GetGuildList();

		for (int i = 0; i < magicnumber; i++)
		{
			if (guilds[i].databaseID != 0)
			{
				leadername[0] = 0;
				Database::Instance()->GetAccountName(guilds[i].leader, leadername);

				if (leadername[0] == 0)
				{
					Message(BLACK, "  DB# %i EQ# %i  <%s>", guilds[i].databaseID, i, guilds[i].name);
				}
				else
				{
					Message(BLACK, "  DB# %i EQ# %i  <%s> Leader: %s", guilds[i].databaseID, i, guilds[i].name, leadername);
				}

				x++;
			}
		}
		Message(BLACK, "%i guilds listed.", x);
	}
	else if (strcasecmp(sep->arg[1], "reload") == 0 && admin >= 100)
	{

		Message(BLACK, "Reloading Guilds");

		int32 eqdbid = atoi(sep->arg[2]);
		zgm.LoadGuilds();
		zgm.SendGuildRefreshPacket(eqdbid);
	}
	else 
	{
		Message(BLACK, "Unknown guild command, try #guild help");
	}
}
コード例 #29
0
    static bool receivedQuery(Client& c, DbResponse& dbresponse, Message& m ) {
        bool ok = true;
        MSGID responseTo = m.header()->id;

        DbMessage d(m);
        QueryMessage q(d);
        auto_ptr< Message > resp( new Message() );

        CurOp& op = *(c.curop());

        shared_ptr<AssertionException> ex;

        try {
            dbresponse.exhaust = runQuery(m, q, op, *resp);
            assert( !resp->empty() );
        }
        catch ( SendStaleConfigException& e ){
            ex.reset( new SendStaleConfigException( e.getns(), e.getInfo().msg ) );
            ok = false;
        }
        catch ( AssertionException& e ) {
            ex.reset( new AssertionException( e.getInfo().msg, e.getCode() ) );
            ok = false;
        }

        if( ex ){

            op.debug().exceptionInfo = ex->getInfo();
            LOGWITHRATELIMIT {
                log() << "assertion " << ex->toString() << " ns:" << q.ns << " query:" <<
                (q.query.valid() ? q.query.toString() : "query object is corrupt") << endl;
                if( q.ntoskip || q.ntoreturn )
                    log() << " ntoskip:" << q.ntoskip << " ntoreturn:" << q.ntoreturn << endl;
            }

            SendStaleConfigException* scex = NULL;
            if ( ex->getCode() == SendStaleConfigCode ) scex = static_cast<SendStaleConfigException*>( ex.get() );

            BSONObjBuilder err;
            ex->getInfo().append( err );
            if( scex ) err.append( "ns", scex->getns() );
            BSONObj errObj = err.done();

            log() << errObj << endl;

            BufBuilder b;
            b.skip(sizeof(QueryResult));
            b.appendBuf((void*) errObj.objdata(), errObj.objsize());

            // todo: call replyToQuery() from here instead of this!!! see dbmessage.h
            QueryResult * msgdata = (QueryResult *) b.buf();
            b.decouple();
            QueryResult *qr = msgdata;
            qr->_resultFlags() = ResultFlag_ErrSet;
            if( scex ) qr->_resultFlags() |= ResultFlag_ShardConfigStale;
            qr->len = b.len();
            qr->setOperation(opReply);
            qr->cursorId = 0;
            qr->startingFrom = 0;
            qr->nReturned = 1;
            resp.reset( new Message() );
            resp->setData( msgdata, true );

        }

        op.debug().responseLength = resp->header()->dataLen();

        dbresponse.response = resp.release();
        dbresponse.responseTo = responseTo;

        return ok;
    }
コード例 #30
0
int main( int argc, char* argv[] )
{

  //lcm 
  lcm::LCM lcm;
  if(!lcm.good())
    return 1;

  vicon_state_t vicon_msg;


  // Program options
  std::string HostName = "192.168.0.101:801";
  if( argc > 1 )
  {
    HostName = argv[1];
  }

  // log contains:
  // version number
  // log of framerate over time
  // --multicast
  // kill off internal app
  std::string LogFile = "";
  std::string MulticastAddress = "244.0.0.0:44801";
  bool ConnectToMultiCast = false;
  bool EnableMultiCast = false;
  bool EnableHapticTest = false;
  bool bReadCentroids = false;
  std::vector<std::string> HapticOnList(0);
  for(int a=2; a < argc; ++a)
  {
    std::string arg = argv[a];
    if(arg == "--help")
    {
      std::cout << argv[0] << " <HostName>: allowed options include:\n  --log_file <LogFile> --enable_multicast <MulticastAddress:Port> --connect_to_multicast <MulticastAddress:Port> --help --enable_haptic_test <DeviceName> --centroids" << std::endl;
      return 0;
    }
    else if (arg=="--log_file")
    {
      if(a < argc)
      {
        LogFile = argv[a+1];
        std::cout << "Using log file <"<< LogFile << "> ..." << std::endl;
        ++a;
      }
    }
    else if (arg=="--enable_multicast")
    {
      EnableMultiCast = true;
      if(a < argc)
      {
        MulticastAddress = argv[a+1];
        std::cout << "Enabling multicast address <"<< MulticastAddress << "> ..." << std::endl;
        ++a;
      }
    }
    else if (arg=="--connect_to_multicast")
    {
      ConnectToMultiCast = true;
      if(a < argc)
      {
        MulticastAddress = argv[a+1];
        std::cout << "connecting to multicast address <"<< MulticastAddress << "> ..." << std::endl;
        ++a;
      }
    }
    else if (arg=="--enable_haptic_test")
    {
      EnableHapticTest = true;
      ++a;
      if ( a < argc )
      {    
        //assuming no haptic device name starts with "--"
        while( a < argc && strncmp( argv[a], "--", 2 ) !=0  )
        {
          HapticOnList.push_back( argv[a] );
          ++a;
        }
      }
    }
    else if( arg=="--centroids" )
    {
      bReadCentroids = true;
    }
    else
    {
      std::cout << "Failed to understand argument <" << argv[a] << ">...exiting" << std::endl;
      return 1;
    }
  }

  std::ofstream ofs;
  if(!LogFile.empty())
  {
    ofs.open(LogFile.c_str());
    if(!ofs.is_open())
    {
      std::cout << "Could not open log file <" << LogFile << ">...exiting" << std::endl;
      return 1;
    }
  }
  // Make a new client
  Client MyClient;

  for(int i=0; i != 3; ++i) // repeat to check disconnecting doesn't wreck next connect
  {
    // Connect to a server
    std::cout << "Connecting to " << HostName << " ..." << std::flush;
    while( !MyClient.IsConnected().Connected )
    {
      // Direct connection

      bool ok = false;
      if(ConnectToMultiCast)
      {
        // Multicast connection
        ok = ( MyClient.ConnectToMulticast( HostName, MulticastAddress ).Result == Result::Success );

      }
      else
      {
        ok =( MyClient.Connect( HostName ).Result == Result::Success );
      }
      if(!ok)
      {
        std::cout << "Warning - connect failed..." << std::endl;
      }


      std::cout << ".";
  #ifdef WIN32
      Sleep( 1000 );
  #else
      sleep(1);
  #endif
    }
    // std::cout << std::endl;

    // Enable some different data types
    MyClient.EnableSegmentData();
    MyClient.EnableMarkerData();
    MyClient.EnableUnlabeledMarkerData();
    MyClient.EnableDeviceData();
    if( bReadCentroids )
    {
      MyClient.EnableCentroidData();
    }

    std::cout << "Segment Data Enabled: "          << Adapt( MyClient.IsSegmentDataEnabled().Enabled )         << std::endl;
    std::cout << "Marker Data Enabled: "           << Adapt( MyClient.IsMarkerDataEnabled().Enabled )          << std::endl;
    std::cout << "Unlabeled Marker Data Enabled: " << Adapt( MyClient.IsUnlabeledMarkerDataEnabled().Enabled ) << std::endl;
    std::cout << "Device Data Enabled: "           << Adapt( MyClient.IsDeviceDataEnabled().Enabled )          << std::endl;
    std::cout << "Centroid Data Enabled: "         << Adapt( MyClient.IsCentroidDataEnabled().Enabled )        << std::endl;

    // Set the streaming mode
    //MyClient.SetStreamMode( ViconDataStreamSDK::CPP::StreamMode::ClientPull );
    // MyClient.SetStreamMode( ViconDataStreamSDK::CPP::StreamMode::ClientPullPreFetch );
    MyClient.SetStreamMode( ViconDataStreamSDK::CPP::StreamMode::ServerPush );

    // Set the global up axis
    MyClient.SetAxisMapping( Direction::Forward, 
                             Direction::Left, 
                             Direction::Up ); // Z-up
    // MyClient.SetGlobalUpAxis( Direction::Forward, 
    //                           Direction::Up, 
    //                           Direction::Right ); // Y-up

    Output_GetAxisMapping _Output_GetAxisMapping = MyClient.GetAxisMapping();
    std::cout << "Axis Mapping: X-" << Adapt( _Output_GetAxisMapping.XAxis ) 
                           << " Y-" << Adapt( _Output_GetAxisMapping.YAxis ) 
                           << " Z-" << Adapt( _Output_GetAxisMapping.ZAxis ) << std::endl;

    // Discover the version number
    Output_GetVersion _Output_GetVersion = MyClient.GetVersion();
    std::cout << "Version: " << _Output_GetVersion.Major << "." 
                             << _Output_GetVersion.Minor << "." 
                             << _Output_GetVersion.Point << std::endl;

    if( EnableMultiCast )
    {
      assert( MyClient.IsConnected().Connected );
      MyClient.StartTransmittingMulticast( HostName, MulticastAddress );
    }

    size_t FrameRateWindow = 1000; // frames
    size_t Counter = 0;
    clock_t LastTime = clock();
    // Loop until a key is pressed
  #ifdef WIN32
    while( !Hit() )
  #else
    while( true)
  #endif
    {
      // Get a frame
      // output_stream << "Waiting for new frame...";
      while( MyClient.GetFrame().Result != Result::Success )
      {
        // Sleep a little so that we don't lumber the CPU with a busy poll
        #ifdef WIN32
          Sleep( 200 );
        #else
          sleep(1);
        #endif

        // output_stream << ".";
      }
      // output_stream << std::endl;
      if(++Counter == FrameRateWindow)
      {
        clock_t Now = clock();
        double FrameRate = (double)(FrameRateWindow * CLOCKS_PER_SEC) / (double)(Now - LastTime);
        if(!LogFile.empty())
        {
          time_t rawtime;
          struct tm * timeinfo;
          time ( &rawtime );
          timeinfo = localtime ( &rawtime );

          ofs << "Frame rate = " << FrameRate << " at " <<  asctime (timeinfo)<< std::endl;
        }

        LastTime = Now;
        Counter = 0;
      }

      // Get the frame number
      Output_GetFrameNumber _Output_GetFrameNumber = MyClient.GetFrameNumber();
      // output_stream << "Frame Number: " << _Output_GetFrameNumber.FrameNumber << std::endl;

      if( EnableHapticTest == true )
      {
        for (size_t i = 0; i < HapticOnList.size(); ++ i)
        {
          if( Counter % 2 == 0 )
          {
              Output_SetApexDeviceFeedback Output= MyClient.SetApexDeviceFeedback( HapticOnList[i],  true ); 
              if( Output.Result == Result::Success )
              {
                // output_stream<< "Turn haptic feedback on for device: " << HapticOnList[i]<<std::endl;
              }
              else if( Output.Result == Result::InvalidDeviceName )
              {
                output_stream<< "Device doesn't exist: "<< HapticOnList[i]<<std::endl;
              }
          }
          if( Counter % 20 == 0 )
          {
              Output_SetApexDeviceFeedback Output = MyClient.SetApexDeviceFeedback( HapticOnList[i],  false); 

              if( Output.Result == Result::Success )
              {
                output_stream<< "Turn haptic feedback off for device: " << HapticOnList[i]<<std::endl;
              }
          }
        }
      }


      // Count the number of subjects
      unsigned int SubjectCount = MyClient.GetSubjectCount().SubjectCount;
      // output_stream << "Subjects (" << SubjectCount << "):" << std::endl;
      for( unsigned int SubjectIndex = 0 ; SubjectIndex < SubjectCount ; ++SubjectIndex )
      {
        // output_stream << "  Subject #" << SubjectIndex << std::endl;

        // Get the subject name
        std::string SubjectName = MyClient.GetSubjectName( SubjectIndex ).SubjectName;
        // output_stream << "    Name: " << SubjectName << std::endl;

        // Get the root segment
        // std::string RootSegment = MyClient.GetSubjectRootSegmentName( SubjectName ).SegmentName;
        // output_stream << "    Root Segment: " << RootSegment << std::endl;

        // Count the number of segments
        unsigned int SegmentCount = MyClient.GetSegmentCount( SubjectName ).SegmentCount;
        // output_stream << "    Segments (" << SegmentCount << "):" << std::endl;
        for( unsigned int SegmentIndex = 0 ; SegmentIndex < SegmentCount ; ++SegmentIndex )
        {
          // output_stream << "      Segment #" << SegmentIndex << std::endl;

          
          // Get the segment name
          std::string SegmentName = MyClient.GetSegmentName( SubjectName, SegmentIndex ).SegmentName;

          //chose the the object by name
          
          if(SegmentName != OBJ_TO_TRACK) continue;
          
          // output_stream << "        Name: " << SegmentName << std::endl;

          // Get the segment parent
          std::string SegmentParentName = MyClient.GetSegmentParentName( SubjectName, SegmentName ).SegmentName;
          // output_stream << "        Parent: " << SegmentParentName << std::endl;

          // Get the segment's children
          unsigned int ChildCount = MyClient.GetSegmentChildCount( SubjectName, SegmentName ).SegmentCount;
          // output_stream << "     Children (" << ChildCount << "):" << std::endl;
          for( unsigned int ChildIndex = 0 ; ChildIndex < ChildCount ; ++ChildIndex )
          {
            std::string ChildName = MyClient.GetSegmentChildName( SubjectName, SegmentName, ChildIndex ).SegmentName;
            // output_stream << "       " << ChildName << std::endl;
          }

          // Get the global segment translation
          Output_GetSegmentGlobalTranslation _Output_GetSegmentGlobalTranslation = 
            MyClient.GetSegmentGlobalTranslation( SubjectName, SegmentName );
          // output_stream << "        Global Translation: (" << _Output_GetSegmentGlobalTranslation.Translation[ 0 ]  << ", " 
                                                       // << _Output_GetSegmentGlobalTranslation.Translation[ 1 ]  << ", " 
                                                       // << _Output_GetSegmentGlobalTranslation.Translation[ 2 ]  << ") " 
                                                       // << Adapt( _Output_GetSegmentGlobalTranslation.Occluded ) << std::endl;

          // Get the global segment rotation in helical co-ordinates
          // Output_GetSegmentGlobalRotationHelical _Output_GetSegmentGlobalRotationHelical = 
          //   MyClient.GetSegmentGlobalRotationHelical( SubjectName, SegmentName );
          // output_stream << "        Global Rotation Helical: (" << _Output_GetSegmentGlobalRotationHelical.Rotation[ 0 ]     << ", " 
                                                            // << _Output_GetSegmentGlobalRotationHelical.Rotation[ 1 ]     << ", " 
                                                            // << _Output_GetSegmentGlobalRotationHelical.Rotation[ 2 ]     << ") " 
                                                            // << Adapt( _Output_GetSegmentGlobalRotationHelical.Occluded ) << std::endl;

          // Get the global segment rotation as a matrix
          Output_GetSegmentGlobalRotationMatrix _Output_GetSegmentGlobalRotationMatrix = 
            MyClient.GetSegmentGlobalRotationMatrix( SubjectName, SegmentName );

            for (int iii = 0; iii < 9; iii ++) {
              vicon_msg.DCM[iii] = _Output_GetSegmentGlobalRotationMatrix.Rotation[ iii ];
            }
            
          // output_stream << "        Global Rotation Matrix: (" << _Output_GetSegmentGlobalRotationMatrix.Rotation[ 0 ]     << ", " 
                                                           // << _Output_GetSegmentGlobalRotationMatrix.Rotation[ 1 ]     << ", " 
                                                           // << _Output_GetSegmentGlobalRotationMatrix.Rotation[ 2 ]     << ", " 
                                                           // << _Output_GetSegmentGlobalRotationMatrix.Rotation[ 3 ]     << ", " 
                                                           // << _Output_GetSegmentGlobalRotationMatrix.Rotation[ 4 ]     << ", " 
                                                           // << _Output_GetSegmentGlobalRotationMatrix.Rotation[ 5 ]     << ", " 
                                                           // << _Output_GetSegmentGlobalRotationMatrix.Rotation[ 6 ]     << ", " 
                                                           // << _Output_GetSegmentGlobalRotationMatrix.Rotation[ 7 ]     << ", " 
                                                           // << _Output_GetSegmentGlobalRotationMatrix.Rotation[ 8 ]     << ") " 
                                                           // << Adapt( _Output_GetSegmentGlobalRotationMatrix.Occluded ) << std::endl;

          // Get the global segment rotation in quaternion co-ordinates
          Output_GetSegmentGlobalRotationQuaternion _Output_GetSegmentGlobalRotationQuaternion = 
            MyClient.GetSegmentGlobalRotationQuaternion( SubjectName, SegmentName );
          // output_stream << "        Global Rotation Quaternion: (" << _Output_GetSegmentGlobalRotationQuaternion.Rotation[ 0 ]     << ", " 
                                                               // << _Output_GetSegmentGlobalRotationQuaternion.Rotation[ 1 ]     << ", " 
                                                               // << _Output_GetSegmentGlobalRotationQuaternion.Rotation[ 2 ]     << ", " 
                                                               // << _Output_GetSegmentGlobalRotationQuaternion.Rotation[ 3 ]     << ") " 
                                                               // << Adapt( _Output_GetSegmentGlobalRotationQuaternion.Occluded ) << std::endl;

          // Get the global segment rotation in EulerXYZ co-ordinates
          Output_GetSegmentGlobalRotationEulerXYZ _Output_GetSegmentGlobalRotationEulerXYZ = 
            MyClient.GetSegmentGlobalRotationEulerXYZ( SubjectName, SegmentName );
            // std::cout<<"global: "<<_Output_GetSegmentGlobalRotationEulerXYZ.Rotation[ 0 ]<<", "<<_Output_GetSegmentGlobalRotationEulerXYZ.Rotation[ 1 ]<<", "<<_Output_GetSegmentGlobalRotationEulerXYZ.Rotation[ 2 ]<<std::endl;
          // output_stream << "        Global Rotation EulerXYZ: (" << _Output_GetSegmentGlobalRotationEulerXYZ.Rotation[ 0 ]     << ", " 
          //                                                    << _Output_GetSegmentGlobalRotationEulerXYZ.Rotation[ 1 ]     << ", " 
          //                                                    << _Output_GetSegmentGlobalRotationEulerXYZ.Rotation[ 2 ]     << ") " 
          //                                                    << Adapt( _Output_GetSegmentGlobalRotationEulerXYZ.Occluded ) << std::endl;


            number = distribution(generator);

            _Output_GetSegmentGlobalTranslation.Translation[ 0 ]+= 1000.0*number;
            _Output_GetSegmentGlobalTranslation.Translation[ 1 ]+= 1000.0*number;
            _Output_GetSegmentGlobalTranslation.Translation[ 2 ]+= 1000.0*number;
            //lcm publish data
            vicon_msg.timestamp = utime_now();
            
            ///////////////////filter position
            // std::cout <<abs(_Output_GetSegmentGlobalTranslation.Translation[ 2 ] - pre_z)<<std::endl;
            // if(abs(_Output_GetSegmentGlobalTranslation.Translation[ 0 ] - pre_x) <= POS_JUMP_THRES)
            addArr(pos_x, _Output_GetSegmentGlobalTranslation.Translation[ 0 ], NUM_SAMPLES_MED);
            // if(abs(_Output_GetSegmentGlobalTranslation.Translation[ 1 ] - pre_y) <= POS_JUMP_THRES) 
            addArr(pos_y, _Output_GetSegmentGlobalTranslation.Translation[ 1 ], NUM_SAMPLES_MED);
            // if(abs(_Output_GetSegmentGlobalTranslation.Translation[ 2 ] - pre_z) <= POS_JUMP_THRES) 
            addArr(pos_z, _Output_GetSegmentGlobalTranslation.Translation[ 2 ], NUM_SAMPLES_MED);

            addArr(pos_x_med, median(pos_x, NUM_SAMPLES_MED), NUM_SAMPLES_AVG);
            addArr(pos_y_med, median(pos_y, NUM_SAMPLES_MED), NUM_SAMPLES_AVG);
            addArr(pos_z_med, median(pos_z, NUM_SAMPLES_MED), NUM_SAMPLES_AVG);

            addArr(pos_x_avg, average(pos_x_med, NUM_SAMPLES_AVG), NUM_SAMPLES_AVG);
            addArr(pos_y_avg, average(pos_y_med, NUM_SAMPLES_AVG), NUM_SAMPLES_AVG);
            addArr(pos_z_avg, average(pos_z_med, NUM_SAMPLES_AVG), NUM_SAMPLES_AVG);


            vicon_msg.position[0] = pos_x_avg[NUM_SAMPLES_AVG - 1];
            vicon_msg.position[1] = pos_y_avg[NUM_SAMPLES_AVG - 1];
            vicon_msg.position[2] = pos_z_avg[NUM_SAMPLES_AVG - 1];

            /////////////////filter attitude
            ///
            ///it seems that attitude is refreshed with half of the frequency as position
            ///
            ///
            addArr(att_x, _Output_GetSegmentGlobalRotationEulerXYZ.Rotation[ 0 ], NUM_SAMPLES_MED);
            addArr(att_y, _Output_GetSegmentGlobalRotationEulerXYZ.Rotation[ 1 ], NUM_SAMPLES_MED);
            addArr(att_z, _Output_GetSegmentGlobalRotationEulerXYZ.Rotation[ 2 ], NUM_SAMPLES_MED);

            addArr(att_x_med, median(att_x, NUM_SAMPLES_MED), NUM_SAMPLES_AVG);
            addArr(att_y_med, median(att_y, NUM_SAMPLES_MED), NUM_SAMPLES_AVG);
            addArr(att_z_med, median(att_z, NUM_SAMPLES_MED), NUM_SAMPLES_AVG);

            addArr(att_x_avg, average(att_x_med, NUM_SAMPLES_AVG), NUM_SAMPLES_AVG);
            addArr(att_y_avg, average(att_y_med, NUM_SAMPLES_AVG), NUM_SAMPLES_AVG);
            addArr(att_z_avg, average(att_z_med, NUM_SAMPLES_AVG), NUM_SAMPLES_AVG);

            vicon_msg.attitude[0] = att_x_avg[NUM_SAMPLES_AVG - 1];
            vicon_msg.attitude[1] = att_y_avg[NUM_SAMPLES_AVG - 1];
            vicon_msg.attitude[2] = att_z_avg[NUM_SAMPLES_AVG - 1];
            // std::cout << "attitude[0]: "<<_Output_GetSegmentGlobalRotationEulerXYZ.Rotation[ 0 ]<<std::endl;
            // std::cout << "attitude[1]: "<<_Output_GetSegmentGlobalRotationEulerXYZ.Rotation[ 1 ]<<std::endl;
            // std::cout << "attitude[2]: "<<_Output_GetSegmentGlobalRotationEulerXYZ.Rotation[ 2 ]<<std::endl;

            dt = (static_cast<double>(vicon_msg.timestamp - time_tmp))/1000; //dt in mseconds

            // differentiate the positions to get velocities
            dx_in_mm = vicon_msg.position[0] - pre_x;
            dy_in_mm = vicon_msg.position[1] - pre_y;
            dz_in_mm = vicon_msg.position[2] - pre_z;

            // std::cout<<"dz: "<<dz_in_mm<<"\tdt: "<<dt <<std::endl;
 
            vx = dx_in_mm/dt;
            vy = dy_in_mm/dt;
            vz = dz_in_mm/dt;

            //differentiate the attitudes to get Euler rate
            v_rho = ((double)vicon_msg.attitude[0] - pre_rho)/(dt/1e3);
            v_theta = ((double)vicon_msg.attitude[1] - pre_theta)/(dt/1e3);
            v_psi = ((double)vicon_msg.attitude[2] - pre_psi)/(dt/1e3);

        ///////////////////////filter the velocity
        //collect data in to stack
        //
           
            //filter out unreasonable jump
            // if(abs(vx - prev_vx) <= JUMP_THRESHOLD) {

            addArr(vel_x, vx, NUM_SAMPLES_MED);
            addArr(vel_x_med, median(vel_x, NUM_SAMPLES_MED), NUM_SAMPLES_AVG);
            addArr(vel_x_avg, average(vel_x_med, NUM_SAMPLES_AVG), NUM_SAMPLES_AVG);

            vx = vel_x_avg[NUM_SAMPLES_AVG-1];

            prev_vx = vx;
              
            // } else vx = prev_vx;

            // if(abs(vy - prev_vy) <= JUMP_THRESHOLD) {
              
            addArr(vel_y, vy, NUM_SAMPLES_MED);
            addArr(vel_y_med, median(vel_y, NUM_SAMPLES_MED), NUM_SAMPLES_AVG);
            addArr(vel_y_avg, average(vel_y_med, NUM_SAMPLES_AVG), NUM_SAMPLES_AVG);

            vy = vel_y_avg[NUM_SAMPLES_AVG-1];

            prev_vy = vy;

            // } else vy = prev_vy;

            // if(abs(vz - prev_vz) <= JUMP_THRESHOLD) {

            addArr(vel_z, vz, NUM_SAMPLES_MED);
            addArr(vel_z_med, median(vel_z, NUM_SAMPLES_MED), NUM_SAMPLES_AVG);
            addArr(vel_z_avg, average(vel_z_med, NUM_SAMPLES_AVG), NUM_SAMPLES_AVG);

            vz = vel_z_avg[NUM_SAMPLES_AVG-1];

            prev_vz = vz;

            // } else vz = prev_vz;


            //filter the Euler rate
            // if(abs(v_rho - v_rho_pre) <= deg2rad(JUMP_THRESHOLD_ATTITUDE)) {

            if(abs(v_rho - v_rho_pre) <= 3) addArr(rho_vel, v_rho, NUM_SAMPLES_MED); // Jump between -180 to 180

            addArr(rho_vel_med, median(rho_vel, NUM_SAMPLES_MED), NUM_SAMPLES_AVG);
            addArr(rho_vel_avg, average(rho_vel_med, NUM_SAMPLES_AVG), NUM_SAMPLES_AVG);
            
            v_rho = rho_vel_avg[NUM_SAMPLES_AVG - 1];

            v_rho_pre = v_rho;
 
            // } else v_rho = v_rho_pre;

            // if(abs(v_theta - v_theta_pre) <= deg2rad(JUMP_THRESHOLD_ATTITUDE)) {

            if(abs(v_theta - v_theta_pre) <= 3) addArr(theta_vel, v_theta, NUM_SAMPLES_MED);

            addArr(theta_vel_med, median(theta_vel, NUM_SAMPLES_MED), NUM_SAMPLES_AVG);
            addArr(theta_vel_avg, average(theta_vel_med, NUM_SAMPLES_AVG), NUM_SAMPLES_AVG);

            v_theta = theta_vel_avg[NUM_SAMPLES_AVG - 1];

            v_theta_pre = v_theta;
              
            // } else v_theta = v_theta_pre;

            // if(abs(v_psi - v_psi_pre) <= deg2rad(JUMP_THRESHOLD_ATTITUDE)) {

            if(abs(v_psi - v_psi_pre) <= 3) addArr(psi_vel, v_psi, NUM_SAMPLES_MED);
            
            addArr(psi_vel_med, median(psi_vel, NUM_SAMPLES_MED), NUM_SAMPLES_AVG);
            addArr(psi_vel_avg, average(psi_vel_med, NUM_SAMPLES_AVG), NUM_SAMPLES_AVG);
            v_psi = psi_vel_avg[NUM_SAMPLES_AVG - 1];

            v_psi_pre = v_psi;

            // } else v_psi = v_psi_pre;

            vicon_msg.velocity[0] = vx;
            vicon_msg.velocity[1] = vy;
            vicon_msg.velocity[2] = vz;

            vicon_msg.angular_vel[0] = v_rho;
            vicon_msg.angular_vel[1] = v_theta;
            vicon_msg.angular_vel[2] = v_psi;

            lcm.publish("vicon_state", &vicon_msg);

            //previous state
            pre_x = (double)vicon_msg.position[0];
            pre_y = (double)vicon_msg.position[1];
            pre_z = (double)vicon_msg.position[2];

            pre_rho = (double)vicon_msg.attitude[0];
            pre_theta = (double)vicon_msg.attitude[1];
            pre_psi = (double)vicon_msg.attitude[2];

            time_tmp = vicon_msg.timestamp;

            //usleep is crucial for accuracy
            usleep(1e4);
        }

      }


      if( bReadCentroids )
      {
        unsigned int CameraCount = MyClient.GetCameraCount().CameraCount;
        output_stream << "Cameras(" << CameraCount << "):" << std::endl;

        for( unsigned int CameraIndex = 0; CameraIndex < CameraCount; ++CameraIndex )
        {
          output_stream << "  Camera #" << CameraIndex << ":" << std::endl;
        
          const std::string CameraName = MyClient.GetCameraName( CameraIndex ).CameraName;
          output_stream << "    Name: " << CameraName << std::endl;

          unsigned int CentroidCount = MyClient.GetCentroidCount( CameraName ).CentroidCount;
          output_stream << "    Centroids(" << CentroidCount << "):" << std::endl;

          for( unsigned int CentroidIndex = 0; CentroidIndex < CentroidCount; ++CentroidIndex )
          {
            output_stream << "      Centroid #" << CentroidIndex << ":" << std::endl;

            Output_GetCentroidPosition _Output_GetCentroidPosition = MyClient.GetCentroidPosition( CameraName, CentroidIndex );
            output_stream << "        Position: (" << _Output_GetCentroidPosition.CentroidPosition[0] << ", "
                                                   << _Output_GetCentroidPosition.CentroidPosition[1] << ")" << std::endl;
            output_stream << "        Radius: ("    << _Output_GetCentroidPosition.Radius   << ")" << std::endl;
            
          }
        }
      }
    }

    if( EnableMultiCast )
    {
      MyClient.StopTransmittingMulticast();
    }
    MyClient.DisableSegmentData();
    MyClient.DisableMarkerData();
    MyClient.DisableUnlabeledMarkerData();
    MyClient.DisableDeviceData();
    if( bReadCentroids )
    {
      MyClient.DisableCentroidData();
    }

    // Disconnect and dispose
    int t = clock();
    std::cout << " Disconnecting..." << std::endl;
    MyClient.Disconnect();
    int dt = clock() - t;
    double secs = (double) (dt)/(double)CLOCKS_PER_SEC;
    std::cout << " Disconnect time = " << secs << " secs" << std::endl;

  }
}