Exemplo n.º 1
0
 public RpcClient()
 {
     taskScanner             = new RpcTaskScanner();
     userProcessors          = new ConcurrentDictionary <Type, UserProcessor>();
     connectionEventHandler  = new RpcConnectionEventHandler(switches());
     connectionEventListener = new ConnectionEventListener();
 }
Exemplo n.º 2
0
        protected override void OnStartup(StartupEventArgs e)
        {
            var cnnService = new FarmingConnectionService();
            var authSnackbarMessageQueue = new SnackbarMessageQueue();
            var cnnViewModel             = new SignInViewModel(cnnService, authSnackbarMessageQueue);
            var authView = new AuthorizationView(cnnViewModel, authSnackbarMessageQueue);

            ConnectionEventHandler onSuccessfulSignIn = null;

            onSuccessfulSignIn = (obj, _e) =>
            {
                cnnService.SuccessfulSignIn -= onSuccessfulSignIn;

                var navigation           = new Navigation();
                var snackbarMessageQueue = new SnackbarMessageQueue();
                var mainViewModel        = new MainViewModel(_e.User, navigation, "FARMING inc.", snackbarMessageQueue);

                MainWindow = new MainWindow(mainViewModel, snackbarMessageQueue);
                authView.Close();
                MainWindow.Show();
            };

            cnnService.SuccessfulSignIn += onSuccessfulSignIn;

            authView.Show();

            base.OnStartup(e);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Raise the NewConnection event
        /// </summary>
        protected void OnNewConnection()
        {
            ConnectionEventHandler newConnection = TCPConnection.NewConnection;

            if (newConnection != null)
            {
                newConnection(this);
            }
        }
Exemplo n.º 4
0
        private void DoPing(ConnectionEventArgs e)
        {
            ConnectionEventHandler handler = OnPing;

            if (handler != null)
            {
                handler(this, e);
            }
        }
Exemplo n.º 5
0
        public static string GetString(string keyName, string defalutValue = "", ConnectionEventHandler failueEventHandler = null)
        {
            if (IsServerDataEnabled(keyName, failueEventHandler))
            {
                Debug.Log("Return server value");
                return(NCMBUser.CurrentUser[keyName].ToString());
            }

            Debug.Log("Return local value");
            return(PlayerPrefs.GetString(keyName, defalutValue));
        }
Exemplo n.º 6
0
        public static float GetFloat(string keyName, float defalutValue = 0f, ConnectionEventHandler failueEventHandler = null)
        {
            if (IsServerDataEnabled(keyName, failueEventHandler))
            {
                Debug.Log("Return server value");
                return((float)NCMBUser.CurrentUser[keyName]);
            }

            Debug.Log("Return local value");
            return(PlayerPrefs.GetFloat(keyName, defalutValue));
        }
Exemplo n.º 7
0
        public static int GetInt(string keyName, int defalutValue = 0, ConnectionEventHandler failueEventHandler = null)
        {
            if (IsServerDataEnabled(keyName, failueEventHandler))
            {
                Debug.Log("Return server value");
                //サーバーに格納される際Int64なのでキャストして取得//
                return((int)Convert.ToInt64(NCMBUser.CurrentUser[keyName]));
            }

            Debug.Log("Return local value");
            return(PlayerPrefs.GetInt(keyName, defalutValue));
        }
        public virtual void TriggerConnectionStateChange(MessageConnection connection,
                                                         string strAction)
        {
            ConnectionEventHandler handler = this.ConnectionStateChange;

            if (handler != null)
            {
                ConnectionEventArgs e = new ConnectionEventArgs();
                e.Action = strAction;
                handler(connection, e);
            }
        }
Exemplo n.º 9
0
        public static void Save(EventHandler successEventHandler, ConnectionEventHandler failureEventHandler = null)
        {
            //まずローカルセーブ//
            SaveLocalTimeStamp();
            PlayerPrefs.Save();

            //ネット接続があるか?//
            if (Application.internetReachability == NetworkReachability.NotReachable)
            {
                if (failureEventHandler != null)
                {
                    failureEventHandler(new ConnectionEventArgs("ネットワークに接続していません。"));
                }

                return;
            }

            //セーブ//
            NCMBUser.CurrentUser.SaveAsync((NCMBException e) =>
            {
                if (e != null)
                {
                    if (failureEventHandler != null)
                    {
                        string errorMessage = string.Empty;

                        if (e.ErrorCode == NCMBException.INCORRECT_HEADER)
                        {
                            errorMessage = "別の端末からログインされています。";
                        }
                        else if (string.IsNullOrEmpty(e.ErrorCode))
                        {
                            errorMessage = "通信が不安定です。";
                        }
                        else
                        {
                            Debug.Log("error: " + e.ErrorCode + " " + e.ErrorMessage);
                        }

                        failureEventHandler(new ConnectionEventArgs(errorMessage));
                    }
                }
                else
                {
                    if (successEventHandler != null)
                    {
                        successEventHandler(null, EventArgs.Empty);
                    }
                }
            }
                                           );
        }
Exemplo n.º 10
0
        protected virtual void OnConnectionEvent(object sender, ConnectionEventArgs e)
        {
            ConnectionEventHandler handler = ConnectionEvent;

            if (e.EventEnum == EventType.Connected)
            {
                isConnected = true;
            }
            else if (e.EventEnum == EventType.Disconnected)
            {
                isConnected = false;
            }

            handler?.Invoke(this, e);
        }
Exemplo n.º 11
0
        public virtual void init(ConnectionEventHandler connectionEventHandler)
        {
            bootstrap = new Bootstrap();

            bootstrap
            .Group(workerGroup)
            .Channel <TcpSocketChannel>()
            .Option(ChannelOption.TcpNodelay, ConfigManager.tcp_nodelay())
            .Option(ChannelOption.SoReuseaddr, ConfigManager.tcp_so_reuseaddr())
            .Option(ChannelOption.SoKeepalive, ConfigManager.tcp_so_keepalive());

            // init netty write buffer water mark
            initWriteBufferWaterMark();

            // init byte buf allocator
            if (ConfigManager.netty_buffer_pooled())
            {
                bootstrap.Option(ChannelOption.Allocator, PooledByteBufferAllocator.Default);
            }
            else
            {
                bootstrap.Option(ChannelOption.Allocator, UnpooledByteBufferAllocator.Default);
            }

            bootstrap.Handler(new ActionChannelInitializer <ISocketChannel>(channel =>
            {
                IChannelPipeline pipeline = channel.Pipeline;
                pipeline.AddLast("decoder", codec.newDecoder());
                pipeline.AddLast("encoder", codec.newEncoder());

                bool idleSwitch = ConfigManager.tcp_idle_switch();
                if (idleSwitch)
                {
                    pipeline.AddLast("idleStateHandler", new IdleStateHandler(TimeSpan.FromMilliseconds(ConfigManager.tcp_idle()), TimeSpan.FromMilliseconds(ConfigManager.tcp_idle()), TimeSpan.FromMilliseconds(0)));
                    pipeline.AddLast("heartbeatHandler", heartbeatHandler);
                }

                pipeline.AddLast("connectionEventHandler", connectionEventHandler);
                pipeline.AddLast("handler", handler);
            }));
        }
Exemplo n.º 12
0
        public Task <object> Get(string varName, string property)
        {
            TaskCompletionSource <object> tcs = new TaskCompletionSource <object>();

            Guid replyId = Guid.NewGuid();

            ConnectionEventHandler <Message, Message> disconnection = null;

            disconnection = (connection) =>
            {
                Disconnected -= disconnection;
                tcs.TrySetCanceled();
            };

            ConnectionMessageEventHandler <Message, Message> fn = null;

            fn = (connection, msg) =>
            {
                if (msg.Id.Equals(replyId))
                {
                    MessageReceived -= fn;
                    tcs.SetResult(msg.Data);
                }
            };

            MessageReceived += fn;
            Disconnected    += disconnection;

            PushMessage(new Message(replyId)
            {
                Command      = Command.Get,
                VariableName = varName,
                Property     = property,
                Data         = null
            });

            return(tcs.Task);
        }
Exemplo n.º 13
0
        private static bool IsServerDataEnabled(string keyName, ConnectionEventHandler failueEventHandler = null)
        {
            //ログインしてる?//
            if (NCMBUser.CurrentUser == null)
            {
                if (failueEventHandler != null)
                {
                    failueEventHandler(new ConnectionEventArgs("ログインしていません。"));
                }
                return(false);
            }
            else if (!NCMBUser.CurrentUser.UpdateDate.HasValue)
            {
                //オンラインに記録した形跡は?//
                Debug.Log("Can't find server save time.");
                return(false);
            }
            else if (!NCMBUser.CurrentUser.ContainsKey(keyName))
            {
                //キーはある?//
                if (failueEventHandler != null)
                {
                    failueEventHandler(new ConnectionEventArgs("キー" + keyName + "は存在しません。"));
                }
                return(false);
            }
            else
            {
                //サーバーとローカル、どっちのデータが新しい?//
                DateTime serverSavedTime = NCMBUser.CurrentUser.UpdateDate.Value;

                serverSavedTime.UtcToLocal();

                DateTime localSavedTime = GetLocalSaveTimeStamp();
                return(serverSavedTime > localSavedTime);
            }
        }
Exemplo n.º 14
0
 private void ConnectionError(string message)
 {
     ConnectionEventHandler?.Invoke(this, (ConnectStatus.ConnectError, message));
 }
Exemplo n.º 15
0
 /// <summary>
 /// Sets the connection event handler. The connection event handler will be called whenever a new
 /// connection was opened, closed, activated, or inactivated.
 /// </summary>
 /// <param name="handler">Handler.</param>
 /// <param name="parameter">Parameter.</param>
 public void SetConnectionEventHandler(ConnectionEventHandler handler, object parameter)
 {
     this.connectionEventHandler          = handler;
     this.connectionEventHandlerParameter = parameter;
 }
Exemplo n.º 16
0
 private void ConnectionSuccess(string message = "")
 {
     ConnectionEventHandler?.Invoke(this, (ConnectStatus.SuccessConnected, message));
 }
Exemplo n.º 17
0
        protected internal override void doInit()
        {
            if (addressParser == null)
            {
                addressParser = new RpcAddressParser();
            }
            if (switches().isOn(GlobalSwitch.SERVER_MANAGE_CONNECTION_SWITCH))
            {
                // in server side, do not care the connection service state, so use null instead of global switch
                ConnectionSelectStrategy connectionSelectStrategy = new RandomSelectStrategy(null);
                connectionManager = new DefaultServerConnectionManager(connectionSelectStrategy);
                connectionManager.startup();

                connectionEventHandler = new RpcConnectionEventHandler(switches());
                connectionEventHandler.ConnectionManager       = connectionManager;
                connectionEventHandler.ConnectionEventListener = connectionEventListener;
            }
            else
            {
                connectionEventHandler = new ConnectionEventHandler(switches());
                connectionEventHandler.ConnectionEventListener = connectionEventListener;
            }
            initRpcRemoting();
            bootstrap = new ServerBootstrap();

            if (IsUseLibuv)
            {
                bootstrap.Channel <TcpServerChannel>();
            }
            else
            {
                bootstrap.Channel <TcpServerSocketChannel>();
            }
            bootstrap.Group(bossGroup, workerGroup)
            .Option(ChannelOption.SoBacklog, ConfigManager.tcp_so_backlog())
            .Option(ChannelOption.SoReuseaddr, ConfigManager.tcp_so_reuseaddr())
            .ChildOption(ChannelOption.TcpNodelay, ConfigManager.tcp_nodelay())
            .ChildOption(ChannelOption.SoKeepalive, ConfigManager.tcp_so_keepalive());

            // set write buffer water mark
            initWriteBufferWaterMark();

            // init byte buf allocator
            if (ConfigManager.netty_buffer_pooled())
            {
                bootstrap
                .Option(ChannelOption.Allocator, PooledByteBufferAllocator.Default)
                .ChildOption(ChannelOption.Allocator, PooledByteBufferAllocator.Default);
            }
            else
            {
                bootstrap
                .Option(ChannelOption.Allocator, UnpooledByteBufferAllocator.Default)
                .ChildOption(ChannelOption.Allocator, PooledByteBufferAllocator.Default);
            }

            // enable trigger mode for epoll if need
            NettyEventLoopUtil.enableTriggeredMode(bootstrap);

            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final boolean idleSwitch = config.ConfigManager.tcp_idle_switch();
            bool idleSwitch = ConfigManager.tcp_idle_switch();
            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final int idleTime = config.ConfigManager.tcp_server_idle();
            int idleTime = ConfigManager.tcp_server_idle();
            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final io.netty.channel.ChannelHandler serverIdleHandler = new ServerIdleHandler();
            IChannelHandler serverIdleHandler = new ServerIdleHandler();
            //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
            //ORIGINAL LINE: final RpcHandler rpcHandler = new RpcHandler(true, this.userProcessors);
            RpcHandler rpcHandler = new RpcHandler(true, userProcessors);

            bootstrap.ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel =>
            {
                IChannelPipeline pipeline = channel.Pipeline;
                pipeline.AddLast("decoder", codec.newDecoder());
                pipeline.AddLast("encoder", codec.newEncoder());
                if (idleSwitch)
                {
                    pipeline.AddLast("idleStateHandler", new IdleStateHandler(TimeSpan.FromMilliseconds(0), TimeSpan.FromMilliseconds(0), TimeSpan.FromMilliseconds(idleTime)));
                    pipeline.AddLast("serverIdleHandler", serverIdleHandler);
                }
                pipeline.AddLast("connectionEventHandler", connectionEventHandler);
                pipeline.AddLast("handler", rpcHandler);

                Url url = addressParser.parse(((IPEndPoint)channel?.RemoteAddress)?.ToString());
                if (switches().isOn(GlobalSwitch.SERVER_MANAGE_CONNECTION_SWITCH))
                {
                    connectionManager.add(new Connection(channel, url), url.UniqueKey);
                }
                else
                {
                    new Connection(channel, url);
                }
                channel.Pipeline.FireUserEventTriggered(ConnectionEventType.CONNECT);
            }));
        }