Exemplo n.º 1
0
        /// <summary>
        /// Force the communicator to sever it's connection.
        /// </summary>
        public void Disconnect()
        {
            lock (this)
            {
                try
                {
                    Connected = false;

                    if (pinger != null)
                    {
                        pinger.Running = false;
                    }

                    if (keepAliveTimer != null)
                    {
                        keepAliveTimer.Dispose();
                    }

                    if (timerThread != null)
                    {
                        timerThread.Interrupt();
                    }

                    if (session != null)
                    {
                        session.destroy_async(new Destroy_Callback());
                    }

                    if (router != null)
                    {
                        router.destroySession_async(new GameRouterDestroySession_Callback());
                    }

                    if (logger != null)
                    {
                        logger.Close();
                    }

                    DestroyAdapter();
                    DestroyCommunicator();
                }
                catch (System.Exception e)
                {
                    logger.Error(
                        "Unexpected error in the Disconnect() method: {0}", e);
                }
                finally
                {
                    pinger         = null;
                    keepAliveTimer = null;
                    session        = null;
                    sessionOneway  = null;
                    router         = null;
                    auth           = null;
                    timerThread    = null;
                    logger         = null;
                }
            }
        }
Exemplo n.º 2
0
        connectImpl(ConnectStrategy factory)
        {
            Debug.Assert(!_destroy);

            try
            {
                _communicator = Ice.Util.initialize(_initData);
            }
            catch (Ice.LocalException ex)
            {
                _destroy = true;
                new Thread(
                    new ThreadStart(delegate()
                {
                    dispatchCallback(delegate()
                    {
                        _callback.connectFailed(this, ex);
                    },
                                     null);
                })).Start();
                return;
            }

            new Thread(new ThreadStart(delegate()
            {
                try
                {
                    dispatchCallbackAndWait(delegate()
                    {
                        _callback.createdCommunicator(this);
                    });

                    Glacier2.RouterPrx routerPrx = Glacier2.RouterPrxHelper.uncheckedCast(
                        _communicator.getDefaultRouter());
                    Glacier2.SessionPrx session = factory(routerPrx);
                    connected(routerPrx, session);
                }
                catch (Exception ex)
                {
                    try
                    {
                        _communicator.destroy();
                    }
                    catch (Exception)
                    {
                    }
                    dispatchCallback(delegate()
                    {
                        _callback.connectFailed(this, ex);
                    }, null);
                }
            })).Start();
        }
Exemplo n.º 3
0
        /// <summary>
        /// Create a proxy pointing to the session factory, which gives the program access to
        /// login methods. If Glacier2 is enabled, it goes through a Glacier2 router.
        /// </summary>
        /// <returns></returns>
        private SessionFactoryPrx CreateSessionFactoryProxy()
        {
            SessionFactoryPrx sessionFactoryProxy = null;

            if (UseGlacier2)
            {
                /*Ice.ObjectPrx routerProxy = communicator.stringToProxy(String.Format(
                 *  "VTank/router:{0} -h {1} -p {2} -t {3}",
                 *      (Secure ? "tcp" : "tcp"), // TODO: We'll eventually use "ssl" for secure connections.
                 *      Host, Port, Timeout));*/
                Ice.ObjectPrx routerProxy = communicator.getDefaultRouter();

                router = Glacier2.RouterPrxHelper.checkedCast(routerProxy);
                if (router == null)
                {
                    // Not a valid Glacier2 router.
                    throw new InvalidHostException(
                              "The target host does not use a Glacier2 router.");
                }

                Glacier2.SessionPrx sessionProxy = router.createSession("MasterCommunicator", "");
                sessionFactoryProxy = SessionFactoryPrxHelper.uncheckedCast(sessionProxy);
            }
            else
            {
                communicator.setDefaultRouter(null);
                sessionFactoryProxy = SessionFactoryPrxHelper.uncheckedCast(
                    communicator.stringToProxy(String.Format(
                                                   "SessionFactory:{0} -h {1} -p {2} -t {3}",
                                                   (Secure ? "tcp" : "tcp"), // TODO: We'll eventually use "ssl" for secure connections.
                                                   Host, Port, Timeout)));
            }

            // Pinging once will initiate the connection and cause an exception to be thrown if
            // the target host is invalid. This is only useful for non-router connections.
            sessionFactoryProxy.ice_ping();

            logger.Info("SessionFactoryProxy created successfully.");

            return(sessionFactoryProxy);
        }
Exemplo n.º 4
0
        public static void LoginAsync(string username, string password,
                                      LoginCallback.LoginSuccessful onSuccess, LoginCallback.LoginFailed onFailure)
        {
            successCallback = onSuccess;
            failureCallback = onFailure;

            string[] args = new string[] { "--Ice.Config=" + CONFIG_FILE };
            comm = Ice.Util.initialize(ref args);

            Ice.ObjectPrx routerPrx = comm.getDefaultRouter();
            router = Glacier2.RouterPrxHelper.checkedCast(routerPrx);
            if (router == null)
            {
                throw new InvalidOperationException(
                          "The target host does not use a Glacier2 router.");
            }

            Glacier2.SessionPrx sessionProxy = router.createSession("CaptainVTank", "");
            sessionFactoryPrx = Main.SessionFactoryPrxHelper.uncheckedCast(sessionProxy);
            sessionFactoryPrx.AdminLogin_async(new LoginCallback(OnLoginSuccess, OnLoginFailure),
                                               username, password, version); // TODO: Use real version.
        }
        public UserSessionPrx loginAndRegister(string userId, string password)
        {
            // log in
            Trace.TraceInformation("Logging in as user [" + userId + "]");
            RouterPrx      glacierRouter  = RouterPrxHelper.checkedCast(communicator.getDefaultRouter());
            UserSessionPrx userSessionPrx = UserSessionPrxHelper.uncheckedCast(glacierRouter.createSession(userId, password));

            Trace.TraceInformation("Login successful!  Session identity = [" + Util.identityToString(userSessionPrx.ice_getIdentity()) + "]");

            // start session pinger
            sessionPinger = startSessionPinger(userSessionPrx);

            // create the servant and its proxy
            Trace.TraceInformation("Creating client servant and proxy");
            ClientServant servant = new ClientServant(new DefaultClientServantEventHandler());
            ObjectAdapter adapter = communicator.createObjectAdapter("Qwerk.Service.Client");

            adapter.activate();
            string        category             = glacierRouter.getServerProxy().ice_getIdentity().category;
            ObjectPrx     servantProxy         = adapter.add(servant, new Identity("clientCallbackReceiver", category));
            TerkClientPrx terkClientServantPrx = TerkClientPrxHelper.uncheckedCast(servantProxy);

            // register ===============================================================================================
            Trace.TraceInformation("Login successful!  Now registering with the relay...");
            try
            {
                userSessionPrx.registerCallbacks(terkClientServantPrx, terkClientServantPrx);
            }
            catch (RegistrationException e)
            {
                Trace.TraceError("RegistrationException while trying to register callbacks with the relay.");
                throw e;
            }
            Trace.TraceInformation("Registration successful!");

            return(userSessionPrx);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Create a proxy pointing to the session factory, which gives the program access to
        /// login methods. If Glacier2 is enabled, it goes through a Glacier2 router.
        /// </summary>
        /// <returns>A proxy pointing to the Auth object adapter on the target server.</returns>
        private AuthPrx CreateAuthProxy()
        {
            AuthPrx authProxy = null;

            if (UseGlacier2)
            {
                Ice.ObjectPrx routerProxy = communicator.stringToProxy(String.Format(
                                                                           "Theatre/router:{0} -h {1} -p {2} -t {3}", "tcp", Host, Port, Timeout));

                router = Glacier2.RouterPrxHelper.checkedCast(routerProxy);
                if (router == null)
                {
                    // Not a valid Glacier2 router.
                    throw new InvalidHostException(
                              "The target host does not use a Glacier2 router.");
                }

                Glacier2.SessionPrx sessionProxy = router.createSession("GameCommunicator", "");
                authProxy = AuthPrxHelper.uncheckedCast(sessionProxy.ice_router(router));
            }
            else
            {
                authProxy = AuthPrxHelper.uncheckedCast(
                    communicator.stringToProxy(String.Format(
                                                   "GameSessionFactory:{0} -h {1} -p {2} -t {3}",
                                                   "tcp", Host, Port, Timeout)));
            }

            // Pinging once will initiate the connection and cause an exception to be thrown if
            // the target host is invalid. This is only useful for non-router connections.
            authProxy.ice_ping();

            logger.Info("AuthProxy created successfully.");

            return(authProxy);
        }
Exemplo n.º 7
0
        public static void LoginAsync(string username, string password,
            LoginCallback.LoginSuccessful onSuccess, LoginCallback.LoginFailed onFailure)
        {
            successCallback = onSuccess;
            failureCallback = onFailure;

            string[] args = new string[] { "--Ice.Config=" + CONFIG_FILE };
            comm = Ice.Util.initialize(ref args);

            Ice.ObjectPrx routerPrx = comm.getDefaultRouter();
            router = Glacier2.RouterPrxHelper.checkedCast(routerPrx);
            if (router == null)
            {
                throw new InvalidOperationException(
                    "The target host does not use a Glacier2 router.");
            }

            Glacier2.SessionPrx sessionProxy = router.createSession("CaptainVTank", "");
            sessionFactoryPrx = Main.SessionFactoryPrxHelper.uncheckedCast(sessionProxy);
            sessionFactoryPrx.AdminLogin_async(new LoginCallback(OnLoginSuccess, OnLoginFailure),
                username, password, version); // TODO: Use real version.
        }
Exemplo n.º 8
0
        connectImpl(ConnectStrategy factory)
        {
            Debug.Assert(!_destroy);

            try
            {
                _communicator = Ice.Util.initialize(_initData);
            }
            catch (Ice.LocalException ex)
            {
                _destroy = true;
                new Thread(
                    new ThreadStart(() =>
                {
                    dispatchCallback(() =>
                    {
                        _callback.connectFailed(this, ex);
                    },
                                     null);
                })).Start();
                return;
            }

            Ice.RouterFinderPrx finder = Ice.RouterFinderPrxHelper.uncheckedCast(_communicator.stringToProxy(_finderStr));
            new Thread(new ThreadStart(() =>
            {
                if (_communicator.getDefaultRouter() == null)
                {
                    try
                    {
                        _communicator.setDefaultRouter(finder.getRouter());
                    }
                    catch (Ice.CommunicatorDestroyedException ex)
                    {
                        dispatchCallback(() =>
                        {
                            _callback.connectFailed(this, ex);
                        }, null);
                        return;
                    }
                    catch (Exception)
                    {
                        //
                        // In case of error getting router identity from RouterFinder use default identity.
                        //
                        Ice.Identity ident = new Ice.Identity("router", "Glacier2");
                        _communicator.setDefaultRouter(Ice.RouterPrxHelper.uncheckedCast(finder.ice_identity(ident)));
                    }
                }

                try
                {
                    dispatchCallbackAndWait(() =>
                    {
                        _callback.createdCommunicator(this);
                    });

                    Glacier2.RouterPrx routerPrx = Glacier2.RouterPrxHelper.uncheckedCast(_communicator.getDefaultRouter());
                    Glacier2.SessionPrx session  = factory(routerPrx);
                    connected(routerPrx, session);
                }
                catch (Exception ex)
                {
                    try
                    {
                        _communicator.destroy();
                    }
                    catch (Exception)
                    {
                    }
                    dispatchCallback(() =>
                    {
                        _callback.connectFailed(this, ex);
                    }, null);
                }
            })).Start();
        }
Exemplo n.º 9
0
        private bool doMain(string[] args, Ice.InitializationData initData, out int status)
        {
            //
            // Reset internal state variables from Ice.Application. The
            // remainder are reset at the end of this method.
            //
            callbackInProgress__ = false;
            destroyed__ = false;
            interrupted__ = false;

            bool restart = false;
            status = 0;

            try
            {
            communicator__ = Ice.Util.initialize(ref args, initData);

            _router = Glacier2.RouterPrxHelper.uncheckedCast(communicator().getDefaultRouter());
            if(_router == null)
            {
                Ice.Util.getProcessLogger().error(appName__ + ": no Glacier2 router configured");
                status = 1;
            }
            else
            {
                //
                // The default is to destroy when a signal is received.
                //
                if(signalPolicy__ == Ice.SignalPolicy.HandleSignals)
                {
                    destroyOnInterrupt();
                }

                //
                // If createSession throws, we're done.
                //
                try
                {
                    _session = createSession();
                    _createdSession = true;
                }
                catch(Ice.LocalException ex)
                {
                    Ice.Util.getProcessLogger().error(ex.ToString());
                    status = 1;
                }

                if(_createdSession)
                {
                    int acmTimeout = 0;
                    try
                    {
                        acmTimeout = _router.getACMTimeout();
                    }
                    catch(Ice.OperationNotExistException)
                    {
                    }
                    if(acmTimeout <= 0)
                    {
                        acmTimeout = (int)_router.getSessionTimeout();
                    }
                    if(acmTimeout > 0)
                    {
                        Ice.Connection connection = _router.ice_getCachedConnection();
                        Debug.Assert(connection != null);
                        connection.setACM((int)acmTimeout, Ice.Util.None, Ice.ACMHeartbeat.HeartbeatAlways);
                        connection.setCloseCallback(_ => sessionDestroyed());
                    }
                    _category = _router.getCategoryForClient();
                    status = runWithSession(args);
                }
            }
            }
            //
            // We want to restart on those exceptions that indicate a
            // break down in communications, but not those exceptions that
            // indicate a programming logic error (i.e., marshal, protocol
            // failure, etc).
            //
            catch(RestartSessionException)
            {
            restart = true;
            }
            catch(Ice.ConnectionRefusedException ex)
            {
            Ice.Util.getProcessLogger().error(ex.ToString());
            restart = true;
            }
            catch(Ice.ConnectionLostException ex)
            {
            Ice.Util.getProcessLogger().error(ex.ToString());
            restart = true;
            }
            catch(Ice.UnknownLocalException ex)
            {
            Ice.Util.getProcessLogger().error(ex.ToString());
            restart = true;
            }
            catch(Ice.RequestFailedException ex)
            {
            Ice.Util.getProcessLogger().error(ex.ToString());
            restart = true;
            }
            catch(Ice.TimeoutException ex)
            {
            Ice.Util.getProcessLogger().error(ex.ToString());
            restart = true;
            }
            catch(Ice.LocalException ex)
            {
            Ice.Util.getProcessLogger().error(ex.ToString());
            status = 1;
            }
            catch(System.Exception ex)
            {
            Ice.Util.getProcessLogger().error("unknown exception:\n" + ex.ToString());
            status = 1;
            }

            //
            // Don't want any new interrupt. And at this point
            // (post-run), it would not make sense to release a held
            // signal to run shutdown or destroy.
            //
            if(signalPolicy__ == Ice.SignalPolicy.HandleSignals)
            {
            ignoreInterrupt();
            }

            lock(mutex__)
            {
            while(callbackInProgress__)
            {
                System.Threading.Monitor.Wait(mutex__);
            }

            if(destroyed__)
            {
                communicator__ = null;
            }
            else
            {
                destroyed__ = true;
                //
                // And communicator__ != null, meaning will be
                // destroyed next, destroyed__ = true also ensures that
                // any remaining callback won't do anything
                //
            }
            }

            if(_createdSession && _router != null)
            {
            try
            {
                _router.destroySession();
            }
            catch(Ice.ConnectionLostException)
            {
                //
                // Expected if another thread invoked on an object from the session concurrently.
                //
            }
            catch(Glacier2.SessionNotExistException)
            {
                //
                // This can also occur.
                //
            }
            catch(System.Exception ex)
            {
                //
                // Not expected.
                //
                Ice.Util.getProcessLogger().error("unexpected exception when destroying the session:\n" +
                                                  ex.ToString());
            }
            _router = null;
            }

            if(communicator__ != null)
            {
            try
            {
                communicator__.destroy();
            }
            catch(Ice.LocalException ex)
            {
                Ice.Util.getProcessLogger().error(ex.ToString());
                status = 1;
            }
            catch(System.Exception ex)
            {
                Ice.Util.getProcessLogger().error("unknown exception:\n" + ex.ToString());
                status = 1;
            }
            communicator__ = null;
            }

            //
            // Reset internal state. We cannot reset the Application state
            // here, since destroyed__ must remain true until we re-run
            // this method.
            //
            _adapter = null;
            _router = null;
            _session = null;
            _createdSession = false;
            _category = null;

            return restart;
        }
Exemplo n.º 10
0
 public SessionPingThread(Application app, Glacier2.RouterPrx router, long period)
 {
     _app = app;
     _router = router;
     _period = period;
     _done = false;
 }