⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 client.cpp

📁 ICE3.3.0--聊天程序服务器端demo
💻 CPP
字号:
// **********************************************************************//// Copyright (c) 2003-2008 ZeroC, Inc. All rights reserved.//// This copy of Chat Demo is licensed to you under the terms// described in the CHAT_DEMO_LICENSE file included in this// distribution.//// **********************************************************************#include <IceUtil/IceUtil.h>#include <Ice/Ice.h>#include <Glacier2/Glacier2.h>#include <ChatSession.h>#include <ChatUtils.h>using namespace std;class SessionRefreshTask : public IceUtil::TimerTask{public:    SessionRefreshTask(const Chat::ChatSessionPrx& session) :        _session(session),        _destroyed(false)    {    }    virtual void    runTimerTask()    {        IceUtil::Mutex::Lock sync(_mutex);        bool destroyed = _destroyed;        sync.release();        if(!destroyed)        {            try            {                _session->ice_ping();            }            catch(const Ice::LocalException& ex)            {                sync.acquire();                _destroyed = true;                //                // ObjecNotExistException is expected because the timer task                // may run after the main thread has destroyed the session.                // Print an error message only for exceptions other than                // ObjectNotExistException.                //                if(!dynamic_cast<const Ice::ObjectNotExistException*>(&ex))                {                    cerr << "session lost:" << ex << endl;                }            }        }    }    bool isDestroyed()    {        IceUtil::Mutex::Lock sync(_mutex);        return _destroyed;    }private:    const Chat::ChatSessionPrx _session;    bool _destroyed;    IceUtil::Mutex _mutex;};typedef IceUtil::Handle<SessionRefreshTask> SessionRefreshTaskPtr;class ChatRoomCallbackI : public Chat::ChatRoomCallback{public:    ChatRoomCallbackI()    {    }    virtual void    init(const Ice::StringSeq& names, const Ice::Current&)    {        cout << "Users: ";        for(Ice::StringSeq::const_iterator it = names.begin(); it != names.end();)        {            cout << *it;            it++;            if(it != names.end())            {                cout << ", ";            }        }        cout << endl;    }    virtual void    join(Ice::Long, const string& name, const Ice::Current&)    {        cout << ">>>> " << name << " joined." << endl;    }    virtual void    leave(Ice::Long, const string& name, const Ice::Current&)    {        cout << "<<<< " << name << " left." << endl;    }    virtual void    send(Ice::Long, const string& name, const string& message, const Ice::Current&)    {        cout << name << " > " << ChatUtils::unstripHtml(message) << endl;    }};class ChatClient : public Ice::Application{public:    ChatClient() :        //        // Since this is an interactive demo we don't want any signal        // handling.        //        Application(Ice::NoSignalHandling)    {    }    virtual int    run(int argc, char* argv[])    {        if(argc > 1)        {            throw string("usage: ") + appName();        }        Chat::ChatSessionPrx session;        Ice::RouterPrx defaultRouter = communicator()->getDefaultRouter();        if(!defaultRouter)        {            throw "no default router set";        }        Glacier2::RouterPrx router = Glacier2::RouterPrx::checkedCast(defaultRouter);        if(!router)        {            throw "configured router is not a Glacier2 router";        }        while(true)        {            cout << "This demo accepts any user ID and password.\n";            string id;            cout << "user id: " << flush;            getline(cin, id);            id = ChatUtils::trim(id);            string pw;            cout << "password: " << flush;            getline(cin, pw);            pw = ChatUtils::trim(pw);            try            {                session = Chat::ChatSessionPrx::uncheckedCast(router->createSession(id, pw));                break;            }            catch(const Glacier2::CannotCreateSessionException& ex)            {                cout << "Login failed:\n" << ex.reason << endl;            }            catch(const Glacier2::PermissionDeniedException& ex)            {                cout << "Login failed:\n" << ex.reason << endl;            }            catch(const Ice::LocalException& ex)            {                cerr << "Communication with the server failed:\n" << ex << endl;            }        }        Ice::ObjectAdapterPtr adapter = communicator()->createObjectAdapterWithRouter("Chat.Client", router);        adapter->activate();        Ice::Identity callbackReceiverIdent;        callbackReceiverIdent.name = "callbackReceiver";        callbackReceiverIdent.category = router->getCategoryForClient();        session->setCallback(Chat::ChatRoomCallbackPrx::uncheckedCast(adapter->add(new ChatRoomCallbackI(),                                                                                   callbackReceiverIdent)));        Ice::Long refreshPeriod = router->getSessionTimeout() / 2;        // Create a TimerTask that periodically refreshes the session proxy to keep it alive.        SessionRefreshTaskPtr refreshTask = new SessionRefreshTask(session);        IceUtil::TimerPtr timer = new IceUtil::Timer();        timer->scheduleRepeated(refreshTask, IceUtil::Time::seconds(refreshPeriod));        menu();        try        {            do            {                string s;                cout << "";                getline(cin, s);                s = ChatUtils::trim(s);                if(!s.empty())                {                    if(s[0] == '/')                    {                        if(s == "/quit")                        {                            break;                        }                        menu();                    }                    else                    {                        try                        {                            ChatUtils::validateMessage(s);                            session->send(s);                        }                        catch(const Chat::InvalidMessageException& ex)                        {                            cout << ex.reason << endl;                        }                    }                }            }            while(cin.good() && !refreshTask->isDestroyed());            if(router)            {                try                {                    router->destroySession();                }                catch(const Ice::LocalException&)                {                }            }            if(timer)            {                timer->destroy();            }        }        catch(const Ice::LocalException& ex)        {            if(router)            {                try                {                    router->destroySession();                }                catch(const Ice::LocalException&)                {                }            }            if(timer)            {                timer->destroy();            }            throw string("Communication with the server failed: ") + ex.ice_name();        }        return EXIT_SUCCESS;    }private:    void    menu()    {        cout << "enter /quit to exit." << endl;    }};intmain(int argc, char* argv[]){    ChatClient app;    return app.main(argc, argv);}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -