Exemplo n.º 1
0
 public ThunkImplementation(ThunkImplementationFactory factory, object instance, Guid instanceId, RpcServer server)
 {
     this.factory    = factory;
     this.instance   = instance;
     this.server     = server;
     this.instanceId = instanceId;
 }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            Log.Texte("", "---------------------------------------------------------------", ConsoleColor.DarkBlue);
            Log.Texte("", " _______ _________ _______ _________ _______  _______          ", ConsoleColor.Cyan);
            Log.Texte("", "(  ____ )\\__   __/(  ____ \\__   __/(  ____ \\(       )|\\     /|", ConsoleColor.Cyan);
            Log.Texte("", "| (    )|   ) (   | (    \\/   ) (   | (    \\/| () () || )   ( |", ConsoleColor.Cyan);
            Log.Texte("", "| (____)|   | |   | (__       | |   | (__    | || || || |   | |", ConsoleColor.Cyan);
            Log.Texte("", "|     __)   | |   |  __)      | |   |  __)   | |(_)| || |   | |", ConsoleColor.Cyan);
            Log.Texte("", "| (\\ (      | |   | (         | |   | (      | |   | || |   | |", ConsoleColor.Cyan);
            Log.Texte("", "| ) \\ \\_____) (___| )         | |   | (____/\\| )   ( || (___) |", ConsoleColor.Cyan);
            Log.Texte("", "|/   \\__/\\_______/|/          )_(   (_______/|/     \\|(_______)", ConsoleColor.Cyan);
            Log.Texte("", "www.Strawberry-Pr0jcts.com", ConsoleColor.DarkCyan);
            Log.Texte("", "---------------------------------------------------------------", ConsoleColor.DarkBlue);

            // Loading all configs files
            ConfigMgr.LoadConfigs();
            Config = ConfigMgr.GetConfig<RealmConfig>();
            Config.RealmInfo.GenerateName();

            // Loading log level from file
            if (!Log.InitLog(Config.LogLevel,"Realm"))
                ConsoleMgr.WaitAndExit(2000);

            CharactersMgr.CharactersDB = DBManager.Start(Config.CharactersDB.Total(), ConnectionType.DATABASE_MYSQL, "Characters");
            if (CharactersMgr.CharactersDB == null)
                ConsoleMgr.WaitAndExit(2000);

            WorldMgr.WorldDB = DBManager.Start(Config.WorldDB.Total(), ConnectionType.DATABASE_MYSQL, "World");
            if (WorldMgr.WorldDB == null)
                ConsoleMgr.WaitAndExit(2000);

            PacketProcessor.RegisterDefinitions();

            // Starting Remote Client
            Client = new RpcClient("Realm-" + Config.RealmInfo.RealmId, Config.RpcCharacter.RpcLocalIp, 1);
            if (!Client.Start(Config.RpcCharacter.RpcServerIp, Config.RpcCharacter.RpcServerPort))
                ConsoleMgr.WaitAndExit(2000);

            Server = new RpcServer(Config.RpcMapServer.RpcClientStartingPort, 2);
            if (!Server.Start(Config.RpcMapServer.RpcIp, Config.RpcMapServer.RpcPort))
                ConsoleMgr.WaitAndExit(2000);

            World = Client.GetLocalObject<WorldMgr>();
            Accounts = Client.GetServerObject<AccountMgr>();
            Characters = Client.GetLocalObject<CharactersMgr>();

            // 1 : Loading WorldMgr
            World.Load();

            // 2 : Loading CharactersMgr
            CharactersMgr.Client = Client;
            CharactersMgr.MyRealm = Config.RealmInfo;
            CharactersMgr.MyRealm.RpcInfo = Client.Info;
            Characters.Load();

            // 3 : Loading AccountsMgr
            Accounts.RegisterRealm(Config.RealmInfo, Client.Info);

            ConsoleMgr.Start();
        }
Exemplo n.º 3
0
        public void unbind()
        {
            var       loggerMock    = AutoMockContainer.GetMock <ILogger <RpcServer> >();
            var       aclLoaderMock = AutoMockContainer.GetMock <INetworkAclLoader>();
            RpcServer rpcServer     = new RpcServer(GetRpcConfig(), loggerMock.Object, aclLoaderMock.Object);

            // binding

            rpcServer.BindOperation(null, "checkDifferent", new Func <int, string, bool>((a, b) =>
            {
                int.TryParse(b, out var bInt);
                return(!bInt.Equals(a));
            }));
            rpcServer.BindController <Foo>();

            // unbinding

            rpcServer.UnbindController("Foo");

            // calling

            var resp = (bool)rpcServer.CallOperation(null, null, "checkDifferent", 2, "2");

            Assert.IsFalse(resp);

            rpcServer.CallOperation(null, "Foo", "Bar");
        }
Exemplo n.º 4
0
        public void bindAndCall()
        {
            var       loggerMock    = AutoMockContainer.GetMock <ILogger <RpcServer> >();
            var       aclLoaderMock = AutoMockContainer.GetMock <INetworkAclLoader>();
            RpcServer rpcServer     = new RpcServer(GetRpcConfig(), loggerMock.Object, aclLoaderMock.Object);

            // binding

            rpcServer.BindOperation(null, "checkDifferent", new Func <int, string, bool>((a, b) =>
            {
                int.TryParse(b, out var bInt);
                return(!bInt.Equals(a));
            }));

            rpcServer.BindOperation("math", "checkEquals", new Func <int, string, bool>((a, b) =>
            {
                int.TryParse(b, out var bInt);
                return(bInt.Equals(a));
            }));

            rpcServer.BindController <MathController>();
            rpcServer.BindController(typeof(Foo));

            // inject

            rpcServer.InjectSpecialParameter(context => new RandomObjectForTest()
            {
                RandomProp = "Hello"
            });

            // calling

            var resp1 = (bool)rpcServer.CallOperation(null, null, "checkDifferent", 2, "2");

            Assert.IsFalse(resp1);

            var resp2 = (bool)rpcServer.CallOperation(null, "math", "checkEquals", new Dictionary <string, object>()
            {
                { "a", 2 },
                { "b", "2" }
            });

            Assert.IsTrue(resp2);

            var resp3 = (int)rpcServer.CallOperation(null, "math", "sum", 2, 3);

            Assert.AreEqual(resp3, 5);

            var resp4 = (int)rpcServer.CallOperation(null, "math", "sub", 3, 1);

            Assert.AreEqual(resp4, 2);

            var resp5 = (string)rpcServer.CallOperation(null, "Foo", "Bar");

            Assert.AreEqual(resp5, "foo bar :)");

            var resp6 = (string)rpcServer.CallOperation(null, "Foo", "PrettyMessage", "how are you?");

            Assert.AreEqual(resp6, "Hello, how are you?");
        }
Exemplo n.º 5
0
        static void Main(string[] args)
        {
            Int32     port      = 13000;
            IPAddress localAddr = IPAddress.Parse("127.0.0.1");

            TcpListener tcpListener = new TcpListener(localAddr, port);

            tcpListener.Start();

            while (true)
            {
                Console.WriteLine("Waiting for a connection...");

                TcpClient tcpClient = tcpListener.AcceptTcpClient();

                Console.WriteLine("Connected!");

                var controller = new RpcController();
                var server     = new RpcServer(controller);

                server.RegisterService <ISampleService>(new SampleService());

                var channel = new NetworkStreamRpcChannel(controller, tcpClient.GetStream());
                channel.Start();

                while (tcpClient.Connected)
                {
                    System.Threading.Thread.Sleep(1000);
                }

                channel.CloseAndJoin();

                Console.WriteLine("Connection closed.\n");
            }
        }
        private void sync(RpcClient client, RpcServer server, int timeout)
        {
            RequestBody b1  = new RequestBody(1, RequestBody.DEFAULT_SYNC_STR);
            object      obj = null;

            try
            {
                if (null == server)
                {
                    obj = client.invokeSync(addr, b1, timeout);
                }
                else
                {
                    Connection conn = client.getConnection(addr, timeout);
                    Assert.NotNull(serverConnectProcessor.Connection);
                    Connection serverConn = serverConnectProcessor.Connection;
                    obj = server.invokeSync(serverConn, b1, timeout);
                }
                Assert.Null("Should not reach here!");
            }
            catch (InvokeTimeoutException)
            {
                Assert.Null(obj);
            }
            catch (RemotingException e)
            {
                logger.LogError("Other RemotingException but RpcServerTimeoutException occurred in sync", e);
                Assert.Null("Should not reach here!");
            }
            catch (ThreadInterruptedException e)
            {
                logger.LogError("ThreadInterruptedException in sync", e);
                Assert.Null("Should not reach here!");
            }
        }
Exemplo n.º 7
0
        public void DemoClientProxyChain()
        {
            Guid iid1 = Guid.NewGuid();
            Guid iid2 = Guid.NewGuid();

            //forward reuests from iid1 to service iid2:
            using (
                RpcServer.CreateRpc(iid1,
                                    new SearchService.ServerStub(
                                        RpcClient.ConnectRpc(iid2, "ncalrpc", null, @"lrpctest").Authenticate(
                                            RpcAuthenticationType.Self)))
                .AddProtocol("ncalrpc", @"lrpctest")
                .AddAuthNegotiate()
                .StartListening())
                //iid calls the implementation
                using (RpcServer.CreateRpc(iid2, new SearchService.ServerStub(new AuthenticatedSearch()))
                       .AddProtocol("ncalrpc", @"lrpctest")
                       .AddAuthNegotiate()
                       .StartListening())
                {
                    using (
                        SearchService client =
                            new SearchService(
                                RpcClient.ConnectRpc(iid1, "ncalrpc", null, @"lrpctest").Authenticate(
                                    RpcAuthenticationType.Self)))
                        Assert.AreEqual(1,
                                        client.Search(SearchRequest.CreateBuilder().AddCriteria(String.Empty).Build()).
                                        ResultsCount);
                }
        }
Exemplo n.º 8
0
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(onError);

            // Loading all configs files
            ConfigMgr.LoadConfigs();
            Config = ConfigMgr.GetConfig<AccountConfigs>();

            // Loading log level from file
            if (!Log.InitLog(Config.LogLevel, "AccountCacher"))
                ConsoleMgr.WaitAndExit(2000);

            AccountMgr.Database = DBManager.Start(Config.AccountDB.Total(), ConnectionType.DATABASE_MYSQL, "Accounts");
            if (AccountMgr.Database == null)
                ConsoleMgr.WaitAndExit(2000);

            Server = new RpcServer(Config.RpcInfo.RpcClientStartingPort, 1);
            if (!Server.Start(Config.RpcInfo.RpcIp, Config.RpcInfo.RpcPort))
                ConsoleMgr.WaitAndExit(2000);

            AcctMgr = Server.GetLocalObject<AccountMgr>();
            AcctMgr.LoadRealms();

            ConsoleMgr.Start();
        }
Exemplo n.º 9
0
        static void Main(string[] args)
        {
            var config = new RpcServerConfiguration();

            config.BindingEndPoint = new IPEndPoint(IPAddress.Loopback, 8089);

            config.PreferIPv4 = true;

            config.IsDebugMode = true;
            //UseFullMethodName is a property that if it is false allows you in the CLIENT to call the         methods only by it's name, check example further.
            config.UseFullMethodName = false;

            var defaultServiceTypeLocator = new DefaultServiceTypeLocator();

            //Methods is the class I created with all the methods to be called.
            defaultServiceTypeLocator.AddService(typeof(Methods));

            config.ServiceTypeLocatorProvider = conf => defaultServiceTypeLocator;

            using (var server = new RpcServer(config))
            {
                server.Start();
                Console.ReadKey();
            }
        }
Exemplo n.º 10
0
        static void Main(string[] args)
        {
            Log.Texte("", "-------------------------------", ConsoleColor.DarkBlue);
            Log.Texte("", "          _____   _____ ", ConsoleColor.Cyan);
            Log.Texte("", "    /\\   |  __ \\ / ____|", ConsoleColor.Cyan);
            Log.Texte("", "   /  \\  | |__) | (___  ", ConsoleColor.Cyan);
            Log.Texte("", "  / /\\ \\ |  ___/ \\___ \\ ", ConsoleColor.Cyan);
            Log.Texte("", " / ____ \\| |     ____) |", ConsoleColor.Cyan);
            Log.Texte("", "/_/    \\_\\_|    |_____/ APB-File", ConsoleColor.Cyan);
            Log.Texte("", "http://AllPrivateServer.com", ConsoleColor.DarkCyan);
            Log.Texte("", "-------------------------------", ConsoleColor.DarkBlue);

            Assembly.Load("Common");

            Log.Info("FileServer", "Starting...");

            ConfigMgr.LoadConfigs();
            Config = ConfigMgr.GetConfig <FileServerConfig>();

            if (!Log.InitLog(Config.LogLevel, "FileServer"))
            {
                ConsoleMgr.WaitAndExit(2000);
            }

            Server = new RpcServer(Config.RpcInfo.RpcClientStartingPort, 0);
            if (!Server.Start(Config.RpcInfo.RpcIp, Config.RpcInfo.RpcPort))
            {
                ConsoleMgr.WaitAndExit(2000);
            }

            Log.Success("FileServer", "Server loaded.");
            ConsoleMgr.Start();
        }
Exemplo n.º 11
0
        static void Main(string[] args)
        {
            Int32 port = 13000;
            IPAddress localAddr = IPAddress.Parse("127.0.0.1");

            TcpListener tcpListener = new TcpListener(localAddr, port);
            tcpListener.Start();

            while (true)
            {
                Console.WriteLine("Waiting for a connection...");

                TcpClient tcpClient = tcpListener.AcceptTcpClient();

                Console.WriteLine("Connected!");

                var controller = new RpcController();
                var server = new RpcServer(controller);

                server.RegisterService<ISampleService>(new SampleService());

                var channel = new NetworkStreamRpcChannel(controller, tcpClient.GetStream());
                channel.Start();

                while (tcpClient.Connected)
                    System.Threading.Thread.Sleep(1000);

                channel.CloseAndJoin();

                Console.WriteLine("Connection closed.\n");
            }
        }
Exemplo n.º 12
0
        private static void StartServer(Type interfaceType, Type implType, string pipeName)
        {
            //create the server
            var controller = new RpcController();

            var server = new RpcServer(controller);

            //register the service with the server. We must specify the interface explicitly since we did not use attributes
            server.GetType()
            .GetMethod("RegisterService")
            .MakeGenericMethod(interfaceType)
            .Invoke(server, new[] { Activator.CreateInstance(implType) });

            //build the connection using named pipes
            try
            {
                pipeServerStreamIn  = CreateNamedPipe(pipeName + "ctos", PipeDirection.In);
                pipeServerStreamOut = CreateNamedPipe(pipeName + "stoc", PipeDirection.Out);
                streamsCreated      = true;
                pipeServerStreamIn.WaitForConnection();
                pipeServerStreamOut.WaitForConnection();

                //create and start the channel which will receive requests
                var channel = new StreamRpcChannel(controller, pipeServerStreamIn, pipeServerStreamOut, useSharedMemory: true);
                channel.Start();
            }
            catch (IOException e)
            {
                //swallow and exit
                Console.WriteLine("Something went wrong (pipes busy?), quitting: " + e);
                throw;
            }
        }
Exemplo n.º 13
0
        public void UpdateNames(RpcServer server)
        {
            if (server.InterfaceId != InterfaceId ||
                server.InterfaceVersion.Major != InterfaceMajorVersion ||
                server.InterfaceVersion.Minor != InterfaceMinorVersion)
            {
                throw new ArgumentException("Name XML doesn't match the server identity");
            }

            if (Structures != null)
            {
                var structures = server.ComplexTypes.OfType <NdrBaseStructureTypeReference>().ToList();
                foreach (var s in Structures)
                {
                    if (structures.Count > s.Index)
                    {
                        s.UpdateNames(structures[s.Index]);
                    }
                }
            }

            if (Procedures != null)
            {
                var procedures = server.Procedures.ToList();
                foreach (var p in Procedures)
                {
                    if (procedures.Count > p.Index)
                    {
                        p.UpdateNames(procedures[p.Index]);
                    }
                }
            }
        }
Exemplo n.º 14
0
        static async Task Main(string[] args)
        {
            RpcServer server = new RpcServer()
            {
                RpcIPAddress = "127.0.0.6",
                RpcPort      = 8007
            };

            RpcServer.Procedures = new Procedures();
            server.LogNotify    += DisplayMessage;
            server.ListenAsync();

            RpcClient client = new RpcClient()
            {
                RpcServerIPAddress = "127.0.0.2",
                RpcServerPort      = 8006
            };

            client.LogNotify += DisplayMessage;

            var r1 = await client.SendRequestAsync(@"{'jsonrpc': '2.0', 'method': 'Sum', 'params': [2,8], 'id': 4}");

            var r2 = await client.SendRequestAsync(@"{'jsonrpc': '2.0', 'method': 'Print', 'id': }");

            Console.WriteLine(r1);
            Console.WriteLine(r2);

            Console.ReadKey();
        }
Exemplo n.º 15
0
        static async Task Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            IClusterClient client = new ClientBuilder().UseLocalhostClustering().Build();

            await client.Connect();

            var container = LoadConfiguration();

            container.RegisterInstance(client.ServiceProvider.GetService <IGrainFactory>());
            RpcServer server = new RpcServer(container.Build())
            {
#if DEBUG
                Debug = true
#endif
            };

            await server.Bind(20170).Run();

            server.Container.Resolve <OrleansChunkViewSynchronizer>().StartSync(server);

            await PrepareTest(client);

            Console.ReadKey();
        }
Exemplo n.º 16
0
        public void PingWithExtensionTest()
        {
            using (RpcServer server = RpcServer.CreateRpc(iid, new SearchService.ServerStub(new AuthenticatedSearch()))
                                      .AddProtocol("ncacn_np", @"\pipe\p1"))
            {
                UnitTestRpcInterop.RegisterAllExtensions(server.ExtensionRegistry);
                server.Ping += delegate(RpcPingRequest r)
                {
                    if (r.HasExtension(UnitTestRpcInterop.CustomPingDataIn))
                    {
                        return(RpcPingResponse.CreateBuilder()
                               .SetExtension(UnitTestRpcInterop.CustomPingDataOut,
                                             r.GetExtension(UnitTestRpcInterop.CustomPingDataIn))
                               .Build());
                    }
                    return(RpcPingResponse.DefaultInstance);
                };
                server.StartListening();

                using (
                    RpcClient client =
                        RpcClient.ConnectRpc(iid, "ncacn_np", null, @"\pipe\p1").Authenticate(
                            RpcAuthenticationType.Anonymous))
                {
                    UnitTestRpcInterop.RegisterAllExtensions(client.ExtensionRegistry);

                    RpcPingRequest r = RpcPingRequest.CreateBuilder()
                                       .SetExtension(UnitTestRpcInterop.CustomPingDataIn, "ping-request-data")
                                       .Build();
                    RpcPingResponse response = client.Ping(r);
                    Assert.IsTrue(response.HasExtension(UnitTestRpcInterop.CustomPingDataOut));
                    Assert.AreEqual("ping-request-data", response.GetExtension(UnitTestRpcInterop.CustomPingDataOut));
                }
            }
        }
Exemplo n.º 17
0
        static void Main(string[] args)
        {
            Log.Texte("", "-------------------------------", ConsoleColor.DarkBlue);
            Log.Texte("", ",---.o", ConsoleColor.Cyan);
            Log.Texte("", "`---..,---.,---.,---.,---.", ConsoleColor.Cyan);
            Log.Texte("", "    |||---'|   ||   |,---|", ConsoleColor.Cyan);
            Log.Texte("", "`---'``---'`   '`   '`---^ Core", ConsoleColor.Cyan);
            Log.Texte("", "http://siennacore.com", ConsoleColor.Blue);
            Log.Texte("", "-------------------------------", ConsoleColor.DarkBlue);


            // Loading log level from file
            if (!Log.InitLog("Configs/Characters.log", "Characters"))
            {
                WaitAndExit();
            }

            // Loading all configs files
            ConfigMgr.LoadConfigs();
            Config = ConfigMgr.GetConfig <CharacterConfig>();

            // Starting Remoting Server
            if (!RpcServer.InitRpcServer("CharacterServer", Config.RpcKey, Config.RpcPort))
            {
                WaitAndExit();
            }

            // Creating Remote objects
            new AccountMgr();
            AccountMgr.AccountDB = DBManager.Start(Config.AccountsDB.Total(), ConnectionType.DATABASE_MYSQL, "Accounts");
            if (AccountMgr.AccountDB == null)
            {
                WaitAndExit();
            }

            new CharacterMgr();
            CharacterMgr.CharacterDB = DBManager.Start(Config.CharactersDB.Total(), ConnectionType.DATABASE_MYSQL, "Characters");
            if (CharacterMgr.CharacterDB == null)
            {
                WaitAndExit();
            }

            new CacheMgr();
            CacheMgr.CharacterDB = DBManager.Start(Config.CharactersDB.Total(), ConnectionType.DATABASE_MYSQL, "Characters");
            if (CacheMgr.CharacterDB == null)
            {
                WaitAndExit();
            }

            CharacterMgr.Instance.LoadRealms();
            CharacterMgr.Instance.LoadCreation_Names();

            // Listening Client
            if (!TCPManager.Listen <RiftServer>(Config.CharacterServerPort, "CharacterServer"))
            {
                WaitAndExit();
            }

            ConsoleMgr.Start();
        }
Exemplo n.º 18
0
 /// <summary>
 /// Creates a new NtCore object to run independently of all other NtCore objects
 /// </summary>
 public IndependentNtCore()
 {
     m_notifier   = new Notifier();
     m_rpcServer  = new RpcServer();
     m_storage    = new Storage(m_notifier, m_rpcServer);
     m_dispatcher = new Dispatcher(m_storage, m_notifier);
 }
Exemplo n.º 19
0
 public void MultiPartMessageTest()
 {
     //Notice that both client and server must enable multi-part messages...
     using (RpcServer.CreateRpc(iid, new SearchService.ServerStub(new AuthenticatedSearch()))
            .AddAuthNegotiate()
            .AddProtocol("ncacn_ip_tcp", "12345")
            .EnableMultiPart()
            .StartListening())
     {
         using (
             SearchService client = new SearchService(RpcClient.ConnectRpc(iid, "ncacn_ip_tcp", "::1", "12345")
                                                      .Authenticate(RpcAuthenticationType.Self).
                                                      EnableMultiPart(1000000)))
         {
             // Non-LRPC channels have limitations on message sizes, we use multiple calls to forward large messages
             // and store state on the server in the RpcSession associated with this client.  This is all transparent
             // to the caller, but this 7 meg message will produce several rpc-calls.
             SearchRequest.Builder criteria = SearchRequest.CreateBuilder();
             byte[] bytes = new byte[2500];
             Random r     = new Random();
             for (int i = 0; i < 2500; i++)
             {
                 r.NextBytes(bytes);
                 criteria.AddCriteria(Convert.ToBase64String(bytes));
             }
             SearchResponse results = client.Search(criteria.Build());
             Assert.AreEqual(2500, results.ResultsCount);
         }
     }
 }
 protected override IDisposable StartServer(int responseSize)
 {
     _service = RpcServer.CreateRpc(Iid, CreateStub(responseSize));
     PrepareService(_service, Iid);
     _service.StartListening();
     return(_service);
 }
Exemplo n.º 21
0
        static void Main(String[] args)
        {
            XTrace.UseConsole();

            var sc = new RpcServer()
            {
                Port       = 1234,
                Log        = XTrace.Log,
                EncoderLog = XTrace.Log,

                NameSpace = "NewLife.Test",
            };

            var star = new StarClient("tcp://127.0.0.1:6666")
            {
                Code   = "test",
                Secret = "pass"
            };

            sc.Star = star;

            sc.Start();

            _Server = sc;

            Thread.Sleep(-1);
        }
Exemplo n.º 22
0
 public void TestServerCreate()
 {
     using (var server = new RpcServer(new TestActorService()))
     {
     }
     Assert.Pass();
 }
Exemplo n.º 23
0
        /// <summary>
        /// Start game server.
        /// <paramref name="period">Span between ticks.</paramref>
        /// </summary>
        public void Run(int period = DefaultPeriod, bool block = true)
        {
            RpcServer.Bind(20170).Run().ContinueWith(s => Logger.Info("Rpc server start ok."));
            Logger.Info("SimCivil loop start running.");

            var token = new CancellationTokenSource();

            Task.Factory.StartNew(
                () => GameLoop(period, token.Token),
                token.Token,
                TaskCreationOptions.LongRunning,
                TaskScheduler.Default)
            // ReSharper disable once MethodSupportsCancellation
            .ContinueWith(t => Logger.Info("SimCivil stop loop."));

            // ReSharper disable once LoopVariableIsNeverChangedInsideLoop
            while (block)
            {
                switch (Console.ReadKey().Key)
                {
                case ConsoleKey.Escape:
                    token.Cancel();
                    Logger.Info("keyboard exit requested");

                    return;
                }
            }
        }
        // ~~~ server invoke test methods

        // ~~~ private methods

        private void oneway(RpcClient client, RpcServer server)
        {
            RequestBody b2 = new RequestBody(2, RequestBody.DEFAULT_ONEWAY_STR);

            try
            {
                if (null == server)
                {
                    client.oneway(addr, b2);
                }
                else
                {
                    Connection conn = client.getConnection(addr, 1000);
                    Assert.NotNull(serverConnectProcessor.Connection);
                    Connection serverConn = serverConnectProcessor.Connection;
                    server.oneway(serverConn, b2);
                }
                Thread.Sleep(50);
            }
            catch (RemotingException e)
            {
                logger.LogError("Exception caught in oneway!", e);
                Assert.Null("Exception caught!");
            }
            catch (ThreadInterruptedException e)
            {
                logger.LogError("ThreadInterruptedException in oneway", e);
                Assert.Null("Should not reach here!");
            }
        }
Exemplo n.º 25
0
        public void DemoExampleConnection()
        {
            //obtain the interface id for rpc registration
            Guid iid = Marshal.GenerateGuidForType(typeof(ISearchService));

            //Create the server with a stub pointing to our implementation
            using (RpcServer.CreateRpc(iid, new SearchService.ServerStub(new AuthenticatedSearch()))
                   //allow GSS_NEGOTIATE
                   .AddAuthNegotiate()
                   //LRPC named 'lrpctest'
                   .AddProtocol("ncalrpc", "lrpctest")
                   .AddProtocol("ncacn_ip_tcp", "12345")
                   .AddProtocol("ncacn_np", @"\pipe\p1")
                   //Begin responding
                   .StartListening())
            {
                // Demonstrate a typical client-implemented wrapper that can parse URIs, retry connections, etc.
                using (var client = new SearchService(new ExampleRpcConnection(iid, "lrpc://localhost/lrpctest")))
                    Assert.AreEqual(1, client.Search(SearchRequest.CreateBuilder().AddCriteria("Test1").Build()).ResultsCount);

                using (var client = new SearchService(new ExampleRpcConnection(iid, "rpc://self@localhost:12345")))
                    Assert.AreEqual(1, client.Search(SearchRequest.CreateBuilder().AddCriteria("Test2").Build()).ResultsCount);

                using (var client = new SearchService(new ExampleRpcConnection(iid, "np://self@localhost/pipe/p1")))
                    Assert.AreEqual(1, client.Search(SearchRequest.CreateBuilder().AddCriteria("Test3").Build()).ResultsCount);
            }
        }
Exemplo n.º 26
0
        public void Init()
        {
            controller = new Mock <RpcController>();

            squareCallMessage                           = new RpcMessage();
            squareCallMessage.Id                        = 42;
            squareCallMessage.CallMessage               = new RpcMessage.Call();
            squareCallMessage.CallMessage.Service       = "ISampleService";
            squareCallMessage.CallMessage.Method        = "GetSquare";
            squareCallMessage.CallMessage.ExpectsResult = true;
            squareCallMessage.CallMessage.Parameters.Add(new RpcMessage.Parameter {
                IntParam = 5
            });

            doStuffCallMessage                     = new RpcMessage();
            doStuffCallMessage.Id                  = 43;
            doStuffCallMessage.CallMessage         = new RpcMessage.Call();
            doStuffCallMessage.CallMessage.Service = "ISampleService";
            doStuffCallMessage.CallMessage.Method  = "DoStuff";
            doStuffCallMessage.CallMessage.Parameters.Add(new RpcMessage.Parameter {
                StringParam = "Hello"
            });

            testParamCallMessage                           = new RpcMessage();
            testParamCallMessage.Id                        = 44;
            testParamCallMessage.CallMessage               = new RpcMessage.Call();
            testParamCallMessage.CallMessage.Service       = "ISampleService";
            testParamCallMessage.CallMessage.ExpectsResult = true;

            server = new RpcServer(controller.Object);

            sampleService = new SampleService();
            server.RegisterService(sampleService);
        }
Exemplo n.º 27
0
        private static void TestSendNotify(int concurrency, Action <IPEndPoint, CountdownEvent, IProducerConsumerCollection <string> > test)
        {
            var endPoint = new IPEndPoint(IPAddress.Loopback, 57319);
            var config   = new RpcServerConfiguration();

            config.BindingEndPoint = endPoint;

            using (var arrivalLatch = new CountdownEvent(concurrency))
            {
                var arriveds = new ConcurrentQueue <string>();
                config.DispatcherProvider =
                    s =>
                    new CallbackDispatcher(
                        s,
                        (id, args) =>
                {
                    arriveds.Enqueue(args[0].ToString());
                    arrivalLatch.Signal();
                    return(args);
                }
                        );
                config.PreferIPv4 = true;

                using (var server = new RpcServer(config))
                    using (var transportManager = new TcpServerTransportManager(server))
                    {
                        test(endPoint, arrivalLatch, arriveds);
                    }
            }
        }
Exemplo n.º 28
0
        static void Main(string[] args)
        {
            Log.Texte("", "-------------------------------", ConsoleColor.DarkBlue);
            Log.Texte("", "          _____   _____ ", ConsoleColor.Cyan);
            Log.Texte("", "    /\\   |  __ \\ / ____|", ConsoleColor.Cyan);
            Log.Texte("", "   /  \\  | |__) | (___  ", ConsoleColor.Cyan);
            Log.Texte("", "  / /\\ \\ |  ___/ \\___ \\ ", ConsoleColor.Cyan);
            Log.Texte("", " / ____ \\| |     ____) |", ConsoleColor.Cyan);
            Log.Texte("", "/_/    \\_\\_|    |_____/ APB-File", ConsoleColor.Cyan);
            Log.Texte("", "http://AllPrivateServer.com", ConsoleColor.DarkCyan);
            Log.Texte("", "-------------------------------", ConsoleColor.DarkBlue);

            Assembly.Load("Common");

            Log.Info("FileServer", "Starting...");

            ConfigMgr.LoadConfigs();
            Config = ConfigMgr.GetConfig<FileServerConfig>();

            if (!Log.InitLog(Config.LogLevel, "FileServer"))
                ConsoleMgr.WaitAndExit(2000);

            Server = new RpcServer(Config.RpcInfo.RpcClientStartingPort, 0);
            if (!Server.Start(Config.RpcInfo.RpcIp, Config.RpcInfo.RpcPort))
                ConsoleMgr.WaitAndExit(2000);

            Log.Success("FileServer", "Server loaded.");
            ConsoleMgr.Start();
        }
Exemplo n.º 29
0
 private RpcClientBuilder(RpcServer server, RpcClientBuilderArguments args)
 {
     _server           = server;
     _type_descriptors = new Dictionary <NdrBaseTypeReference, RpcTypeDescriptor>();
     _args             = args;
     _proc_names       = new HashSet <string>();
 }
Exemplo n.º 30
0
        static void Main(string[] args)
        {
            var options = new RpcServerOptions();

            options.callback = Program.Callback;
            var rpcServer = RpcServer.Create(options);
        }
Exemplo n.º 31
0
        public void DemoRpcOverLrpc()
        {
            //obtain the interface id for rpc registration
            Guid iid = Marshal.GenerateGuidForType(typeof(ISearchService));

            //Create the server with a stub pointing to our implementation
            using (RpcServer.CreateRpc(iid, new SearchService.ServerStub(new AuthenticatedSearch()))
                   //allow GSS_NEGOTIATE
                   .AddAuthNegotiate()
                   //LRPC named 'lrpctest'
                   .AddProtocol("ncalrpc", "lrpctest")
                   //Begin responding
                   .StartListening())
            {
                //Create the rpc client connection and give it to the new SearchService
                using (
                    SearchService client =
                        new SearchService(
                            RpcClient.ConnectRpc(iid, "ncalrpc", null, "lrpctest").Authenticate(
                                RpcAuthenticationType.Self)))
                {
                    //party on!
                    SearchResponse results =
                        client.Search(SearchRequest.CreateBuilder().AddCriteria("Test Criteria").Build());
                    Assert.AreEqual(1, results.ResultsCount);
                    Assert.AreEqual("Test Criteria", results.ResultsList[0].Name);
                    Assert.AreEqual("http://whatever.com", results.ResultsList[0].Url);
                }
            }
        }
Exemplo n.º 32
0
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(onError);

            Log.Texte("", "-------------------- Account Cacher  -------------------", ConsoleColor.DarkRed);

            // Loading all configs files
            ConfigMgr.LoadConfigs();
            Config = ConfigMgr.GetConfig <AccountConfigs>();

            // Loading log level from file
            if (!Log.InitLog(Config.LogLevel, "AccountCacher"))
            {
                ConsoleMgr.WaitAndExit(2000);
            }

            AccountMgr.Database = DBManager.Start(Config.AccountDB.Total(), Config.AccountDB.ConnectionType, "Accounts", Config.AccountDB.Database);
            if (AccountMgr.Database == null)
            {
                ConsoleMgr.WaitAndExit(2000);
            }

            Server = new RpcServer(Config.RpcInfo.RpcClientStartingPort, 1);
            if (!Server.Start(Config.RpcInfo.RpcIp, Config.RpcInfo.RpcPort))
            {
                ConsoleMgr.WaitAndExit(2000);
            }

            AcctMgr = Server.GetLocalObject <AccountMgr>();
            AcctMgr.LoadRealms();

            ConsoleMgr.Start();
        }
 internal ModifiedRpcServerResult(RpcServer server, RpcServer compare_server,
                                  IEnumerable <NdrProcedureDefinition> added_procedure)
 {
     Server         = server;
     CompareServer  = compare_server;
     AddedProcedure = added_procedure.ToList().AsReadOnly();
 }
Exemplo n.º 34
0
        private static void StartServer(Type interfaceType, Type implType, string pipeName)
        {
            //create the server
            var controller = new RpcController();
            
            var server = new RpcServer(controller);

            //register the service with the server. We must specify the interface explicitly since we did not use attributes
            server.GetType()
                  .GetMethod("RegisterService")
                  .MakeGenericMethod(interfaceType)
                  .Invoke(server, new[] {Activator.CreateInstance(implType)});

            //build the connection using named pipes
            try
            {
                pipeServerStreamIn = CreateNamedPipe(pipeName + "ctos", PipeDirection.In);
                pipeServerStreamOut = CreateNamedPipe(pipeName + "stoc", PipeDirection.Out);
                streamsCreated = true;
                pipeServerStreamIn.WaitForConnection();
                pipeServerStreamOut.WaitForConnection();
                
                //create and start the channel which will receive requests
                var channel = new StreamRpcChannel(controller, pipeServerStreamIn, pipeServerStreamOut, useSharedMemory: true);
                channel.Start();
            }
            catch (IOException e)
            {
                //swallow and exit
                Console.WriteLine("Something went wrong (pipes busy?), quitting: " + e);
                throw;
            }
        }
Exemplo n.º 35
0
        static void Main(string[] args)
        {
            Log.Texte("", "-------------------------------", ConsoleColor.DarkBlue);
            Log.Texte("", "          _____   _____ ", ConsoleColor.Cyan);
            Log.Texte("", "    /\\   |  __ \\ / ____|", ConsoleColor.Cyan);
            Log.Texte("", "   /  \\  | |__) | (___  ", ConsoleColor.Cyan);
            Log.Texte("", "  / /\\ \\ |  ___/ \\___ \\ ", ConsoleColor.Cyan);
            Log.Texte("", " / ____ \\| |     ____) |", ConsoleColor.Cyan);
            Log.Texte("", "/_/    \\_\\_|    |_____/ APB-Char", ConsoleColor.Cyan);
            Log.Texte("", "http://AllPrivateServer.com", ConsoleColor.DarkCyan);
            Log.Texte("", "-------------------------------", ConsoleColor.DarkBlue);

            Assembly.Load("Common");

            Log.Info("CharacterServer", "Starting...");

            ConfigMgr.LoadConfigs();
            Config = ConfigMgr.GetConfig<CharacterServerConfig>();

            if (!Log.InitLog(Config.LogLevel, "CharacterServer"))
                ConsoleMgr.WaitAndExit(2000);

            CharacterMgr.Database = DBManager.Start(Config.CharacterDatabase.Total(), ConnectionType.DATABASE_MYSQL, "CharDB");
            if(CharacterMgr.Database == null)
                ConsoleMgr.WaitAndExit(2000);

            Server = new RpcServer(Config.RpcInfo.RpcClientStartingPort, 0);
            if (!Server.Start(Config.RpcInfo.RpcIp, Config.RpcInfo.RpcPort))
                ConsoleMgr.WaitAndExit(2000);

            Log.Success("CharacterServer", "Server loaded.");
            ConsoleMgr.Start();
        }
Exemplo n.º 36
0
        public virtual void testStopRepeatedly()
        {
            RpcServer rpcServer = new RpcServer(1111);

            try
            {
                rpcServer.startup();
            }
            catch (Exception e)
            {
                Assert.Null("Should not reach here!");
                Console.WriteLine(e.ToString());
                Console.Write(e.StackTrace);
            }
            rpcServer.shutdown();
            try
            {
                rpcServer.shutdown();
                Assert.Null("Should not reach here!");
            }
            catch (Exception)
            {
                // expect IllegalStateException
            }
        }
Exemplo n.º 37
0
        public void Start()
        {
            if (mServer.IsRunning)
            {
                return;
            }

            var controller = new RpcController();
            var server     = new RpcServer(controller);

            server.RegisterService(mJournal);

            mServer.Start(Settings.Port, Settings.NumberOfConnections);

            mServer.SocketProcessing = client =>
            {
                using (var channel = new TcpClientRpcChannel(controller, client, 5000))                               //, "server"))
                {
                    Console.WriteLine("Server get req RPC DATA ->>");

                    channel.Start();
                    channel.OnError = () => Console.WriteLine("Error: RPC channel not started: controller RPC,client socket, or port 5000");

                    while (channel.IsReady)
                    {
                        Thread.Sleep(50);
                    }

                    //Thread.Sleep(3000);

                    Console.WriteLine("<<-RPC DATA");
                }
            };
        }
Exemplo n.º 38
0
		private static void TestCore( Action<ServerRequestContext, ServerTransport> test )
		{
			using ( var server = new RpcServer() )
			using ( var manager = new NullServerTransportManager( server ) )
			using ( var transport = new NullServerTransport( manager ) )
			using ( var target = new ServerRequestContext() )
			{
				test( target, transport );
			}
		}
Exemplo n.º 39
0
		public void TestDispose()
		{
			using ( var server = new RpcServer() )
			using ( var target = new Target( server ) )
			{
				target.Dispose();

				Assert.That( target.GetIsDisposed(), Is.True );
				Assert.That( target.DisposeCalled, Is.True );
			}
		}
Exemplo n.º 40
0
        public async Task StartAsync(string port)
        {
            if (_isDisposed)
                throw new ObjectDisposedException(nameof(NetGameServer));

            if (_rpcServer != null)
                throw new InvalidOperationException();

            var serializer = new DefaultJsonSerializer(typeof(NetGameServer).GetTypeInfo().Assembly, Serialization.JsonSerializationSettings);
            _rpcServer = await RpcServer.StartAsync(port, this, serializer);
        }
        public void Init()
        {
            var controller = new RpcController();
            client = new RpcClient(controller);
            server = new RpcServer(controller);
            server.RegisterService(new SampleService());
            var channel = new LoopbackRpcChannel(controller);
            channel.Start();

            dynProxy = client.GetProxy("ISampleService");
        }
		public void TestDispatch_MethodExists_Success()
		{
			var svcFile = ".\\Services.svc";
			File.WriteAllText(
				svcFile,
				String.Format( CultureInfo.InvariantCulture, "<% @ ServiceHost Service=\"{0}\" %>", typeof( TestService ).FullName )
			);
			try
			{
				var configuration = new RpcServerConfiguration();
				configuration.ServiceTypeLocatorProvider = conf => new FileBasedServiceTypeLocator();

				using ( var server = new RpcServer( configuration ) )
				using ( var transportManager = new NullServerTransportManager( server ) )
				using ( var transport = new NullServerTransport( transportManager ) )
				using ( var requestContext = DispatchTestHelper.CreateRequestContext() )
				using ( var argumentsBuffer = new MemoryStream() )
				using ( var waitHandle = new ManualResetEventSlim() )
				{
					var message = Guid.NewGuid().ToString();
					using ( var argumentsPacker = Packer.Create( argumentsBuffer, false ) )
					{
						argumentsPacker.PackArrayHeader( 1 );
						argumentsPacker.Pack( message );
					}

					argumentsBuffer.Position = 0;

					var target = new LocatorBasedDispatcher( server );
					MessagePackObject response = MessagePackObject.Nil;
					requestContext.MethodName = "Echo:TestService:1";
					requestContext.MessageId = 1;
					requestContext.SetTransport( transport );
					requestContext.ArgumentsUnpacker = Unpacker.Create( argumentsBuffer );
					transport.Sent +=
						( sender, e ) =>
						{
							response = Unpacking.UnpackString( e.Context.GetReturnValueData() ).Value;
							waitHandle.Set();
						};
					target.Dispatch( transport, requestContext );

					Assert.That( waitHandle.Wait( TimeSpan.FromSeconds( 1 ) ) );

					Assert.That( message == response, "{0} != {1}", message, response );
				}
			}
			finally
			{
				File.Delete( svcFile );
			}
		}
Exemplo n.º 43
0
		/// <summary>
		/// Initializes a new instance of the <see cref="LocatorBasedDispatcher"/> class.
		/// </summary>
		/// <param name="server">The server which will hold this instance.</param>
		/// <exception cref="ArgumentNullException">
		///		<paramref name="server"/> is <c>null</c>.
		/// </exception>
		public LocatorBasedDispatcher( RpcServer server )
			: base( server )
		{
			this._locator = server.Configuration.ServiceTypeLocatorProvider( server.Configuration );
			this._descriptionTable = server.Configuration.UseFullMethodName ? new VersionedOperationCatalog() : ( OperationCatalog )new FlatOperationCatalog();

			foreach ( var service in this._locator.FindServices() )
			{
				foreach ( var operation in OperationDescription.FromServiceDescription( this.Runtime, service ) )
				{
					this._descriptionTable.Add( operation );
				}
			}
		}
Exemplo n.º 44
0
        public async Task DisposeAsync()
        {
            if (!_isDisposed)
            {
                _isDisposed = true;

                if (_rpcServer != null)
                {
                    // Closing the server will disconnect all clients
                    // => OnDisconnected will correctly remove players from the game
                    await _rpcServer.DisposeAsync();
                    _rpcServer = null;
                }
            }
        }
Exemplo n.º 45
0
        static void Main(string[] args)
        {
            Log.Texte("", "---------------------------------------------------------------", ConsoleColor.DarkBlue);
            Log.Texte("", " _______ _________ _______ _________ _______  _______          ", ConsoleColor.Cyan);
            Log.Texte("", "(  ____ )\__   __/(  ____ \\__   __/(  ____ \(       )|\     /|", ConsoleColor.Cyan);
            Log.Texte("", "| (    )|   ) (   | (    \/   ) (   | (    \/| () () || )   ( |", ConsoleColor.Cyan);
            Log.Texte("", "| (____)|   | |   | (__       | |   | (__    | || || || |   | |", ConsoleColor.Cyan);
            Log.Texte("", "|     __)   | |   |  __)      | |   |  __)   | |(_)| || |   | |", ConsoleColor.Cyan);
            Log.Texte("", "| (\ (      | |   | (         | |   | (      | |   | || |   | |", ConsoleColor.Cyan);
            Log.Texte("", "| ) \ \_____) (___| )         | |   | (____/\| )   ( || (___) |", ConsoleColor.Cyan);
            Log.Texte("", "|/   \__/\_______/|/          )_(   (_______/|/     \|(_______)", ConsoleColor.Cyan);
            Log.Texte("", "www.Strawberry-Pr0jcts.com", ConsoleColor.DarkCyan);
            Log.Texte("", "---------------------------------------------------------------", ConsoleColor.DarkBlue);

            // Loading all configs files
            ConfigMgr.LoadConfigs();
            Config = ConfigMgr.GetConfig<CharacterConfig>();

            // Loading log level from file
            if (!Log.InitLog(Config.LogLevel,"Character"))
                ConsoleMgr.WaitAndExit(2000);

            AccountMgr.AccountDB = DBManager.Start(Config.AccountDB.Total(), ConnectionType.DATABASE_MYSQL, "Accounts");
            if (AccountMgr.AccountDB == null)
                ConsoleMgr.WaitAndExit(2000);

            // Starting Remote Server
            Server = new RpcServer(Config.RpcClientStartingPort, 1);
            if (!Server.Start(Config.RpcIP, Config.RpcPort))
                ConsoleMgr.WaitAndExit(2000);

            // Starting Accounts Manager
            AcctMgr = Server.GetLocalObject<AccountMgr>();
            if(AcctMgr == null)
                ConsoleMgr.WaitAndExit(2000);

            AcctMgr.LoadRealms();

            // Listening Client
            if (!TCPManager.Listen<RiftServer>(Config.CharacterServerPort, "CharacterServer"))
                ConsoleMgr.WaitAndExit(2000);

            ConsoleMgr.Start();
        }
		private static void TestSendReceiveRequest( Action<IPEndPoint, UdpServerTransportManager> test )
		{
			var endPoint = new IPEndPoint( IPAddress.Loopback, 57319 );
			var config = new RpcServerConfiguration();
			config.BindingEndPoint = endPoint;
			config.DispatcherProvider =
				s =>
					new CallbackDispatcher(
						s,
						( id, args ) => args
					);
			config.PreferIPv4 = true;

			using ( var server = new RpcServer( config ) )
			using ( var transportManager = new UdpServerTransportManager( server ) )
			{
				test( endPoint, transportManager );
			}
		}
Exemplo n.º 47
0
        static void Main(string[] args)
        {
            Log.Texte("", "-------------------------------",    ConsoleColor.DarkBlue);
            Log.Texte("", "          _____   _____ ",           ConsoleColor.Cyan);
            Log.Texte("", "    /\\   |  __ \\ / ____|",         ConsoleColor.Cyan);
            Log.Texte("", "   /  \\  | |__) | (___  ",          ConsoleColor.Cyan);
            Log.Texte("", "  / /\\ \\ |  ___/ \\___ \\ ",       ConsoleColor.Cyan);
            Log.Texte("", " / ____ \\| |     ____) |",          ConsoleColor.Cyan);
            Log.Texte("", "/_/    \\_\\_|    |_____/ Rift",     ConsoleColor.Cyan);
            Log.Texte("", "http://AllPrivateServer.com",        ConsoleColor.DarkCyan);
            Log.Texte("", "-------------------------------",    ConsoleColor.DarkBlue);

            // Loading all configs files
            ConfigMgr.LoadConfigs();
            Config = ConfigMgr.GetConfig<CharacterConfig>();

            // Loading log level from file
            if (!Log.InitLog(Config.LogLevel,"Character"))
                ConsoleMgr.WaitAndExit(2000);

            AccountMgr.AccountDB = DBManager.Start(Config.AccountDB.Total(), ConnectionType.DATABASE_MYSQL, "Accounts");
            if (AccountMgr.AccountDB == null)
                ConsoleMgr.WaitAndExit(2000);

            // Starting Remote Server
            Server = new RpcServer(Config.RpcClientStartingPort, 1);
            if (!Server.Start(Config.RpcIP, Config.RpcPort))
                ConsoleMgr.WaitAndExit(2000);

            // Starting Accounts Manager
            AcctMgr = Server.GetLocalObject<AccountMgr>();
            if(AcctMgr == null)
                ConsoleMgr.WaitAndExit(2000);

            AcctMgr.LoadRealms();

            // Listening Client
            if (!TCPManager.Listen<RiftServer>(Config.CharacterServerPort, "CharacterServer"))
                ConsoleMgr.WaitAndExit(2000);

            ConsoleMgr.Start();
        }
Exemplo n.º 48
0
		public void TestRaiseServerError_RpcServerServerErrorEventOccurredWithSpeicifiedValues()
		{
			bool occurred = false;
			using ( var server = new RpcServer() )
			using ( var context = new ServerRequestContext() )
			{
				var exception = new InvalidOperationException();
				server.ServerError +=
					( sender, e ) =>
					{
						Assert.That( e.Exception, Is.EqualTo( exception ) );
						occurred = true;
					};
				using ( var target = new Target( server ) )
				{
					target.RaiseServerError( exception );
					Assert.That( occurred );
				}
			}
		}
Exemplo n.º 49
0
        static async Task MainAsync()
        {
            var server = new RpcServer("127.0.0.1", 3000, conn =>
            {
                conn.On("Hello1", (string name) => string.Format("hello {0}", name));

                conn.On("Hello2", async () =>
                {
                    var name = await conn.Call<string>("GetName");
                    return string.Format("hello {0}", name);
                });

                conn.On("Add", (int num1, int num2) => num1 + num2);

                conn.On("Test", (TestClass o) => o.Member.ToLower());
            });

            var client = new RpcClient("127.0.0.1", 3000);
            client.On("GetName", () => "Rohan");

            client.Connected += async () =>
            {
                try
                {
                    Console.WriteLine("Hello1: {0}", await client.Call<string, string>("Hello1", "Brian"));

                    Console.WriteLine("Hello2: {0}", await client.Call<string>("Hello2"));

                    Console.WriteLine("Add: {0}", await client.Call<int, int, int>("Add", 10, 301));

                    Console.WriteLine("Test: {0}", await client.Call<TestClass, string>("Test", new TestClass { Member = "HELP" }));
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            };

            // give the client some time to connect
            await Task.Delay(500);
        }
Exemplo n.º 50
0
		public void TestRaiseClientError_RpcServerClientErrorEventOccurredWithSpeicifiedValues()
		{
			bool occurred = false;
			using ( var server = new RpcServer() )
			using ( var context = new ServerRequestContext() )
			{
				var error = RpcError.ArgumentError;
				server.ClientError +=
					( sender, e ) =>
					{
						Assert.That( e.MessageId, Is.EqualTo( context.MessageId ) );
						Assert.That( e.RemoteEndPoint, Is.EqualTo( context.RemoteEndPoint ) );
						Assert.That( e.RpcError.Error, Is.EqualTo( error ) );
						Assert.That( e.SessionId, Is.EqualTo( context.SessionId ) );
						occurred = true;
					};
				using ( var target = new Target( server ) )
				{
					target.RaiseClientError( context, new RpcErrorMessage( error, "Test" ) );
					Assert.That( occurred );
				}
			}
		}
Exemplo n.º 51
0
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(onError);

            Log.Texte("", "-------------------- Account Cacher -------------------", ConsoleColor.DarkRed);
            Log.Texte("", " █     █░ ▄▄▄       ██▀███  ▓█████  ███▄ ▄███▓ █    ██ ", ConsoleColor.Red);
            Log.Texte("", "▓█░ █ ░█░▒████▄    ▓██ ▒ ██▒▓█   ▀ ▓██▒▀█▀ ██▒ ██  ▓██▒", ConsoleColor.Red);
            Log.Texte("", "▒█░ █ ░█ ▒██  ▀█▄  ▓██ ░▄█ ▒▒███   ▓██    ▓██░▓██  ▒██░", ConsoleColor.Red);
            Log.Texte("", "░█░ █ ░█ ░██▄▄▄▄██ ▒██▀▀█▄  ▒▓█  ▄ ▒██    ▒██ ▓▓█  ░██░", ConsoleColor.Red);
            Log.Texte("", "░░██▒██▓  ▓█   ▓██▒░██▓ ▒██▒░▒████▒▒██▒   ░██▒▒▒█████▓ ", ConsoleColor.Red);
            Log.Texte("", "░ ▓░▒ ▒   ▒▒   ▓▒█░░ ▒▓ ░▒▓░░░ ▒░ ░░ ▒░   ░  ░░▒▓▒ ▒ ▒ ", ConsoleColor.Red);
            Log.Texte("", "  ▒ ░ ░    ▒   ▒▒ ░  ░▒ ░ ▒░ ░ ░  ░░  ░      ░░░▒░ ░ ░ ", ConsoleColor.Red);
            Log.Texte("", "  ░   ░    ░   ▒     ░░   ░    ░   ░      ░    ░░░ ░ ░ ", ConsoleColor.Red);
            Log.Texte("", "    ░          ░  ░   ░        ░  ░       ░      ░    ", ConsoleColor.Red);
            Log.Texte("", "-------------------http://WarEmu.com-------------------", ConsoleColor.DarkRed);

            // Loading all configs files
            ConfigMgr.LoadConfigs();
            Config = ConfigMgr.GetConfig<AccountConfigs>();

            // Loading log level from file
            if (!Log.InitLog(Config.LogLevel, "AccountCacher"))
                ConsoleMgr.WaitAndExit(2000);

            AccountMgr.Database = DBManager.Start(Config.AccountDB.Total(), ConnectionType.DATABASE_MYSQL, "Accounts");
            if (AccountMgr.Database == null)
                ConsoleMgr.WaitAndExit(2000);

            Server = new RpcServer(Config.RpcInfo.RpcClientStartingPort, 1);
            if (!Server.Start(Config.RpcInfo.RpcIp, Config.RpcInfo.RpcPort))
                ConsoleMgr.WaitAndExit(2000);

            AcctMgr = Server.GetLocalObject<AccountMgr>();
            AcctMgr.LoadRealms();

            ConsoleMgr.Start();
        }
Exemplo n.º 52
0
        static void Main(string[] args)
        {
            serviceDefinition = ServiceInfoFactory.CreateServiceDefinition(new ServiceInfo { Port = Convert.ToInt32(ServiceConfig.Reader.Port) });

            var store = new RegistryDatabaseFactory();
            store.Create();
            store.ApplySchema();
            store.r.Connection.Dispose();

            if (args.Length == 0 || args.Contains("-ampq"))
            {
                serviceRegistryServer = new RpcServer<ServiceInfo>(ConnectionConfig.GetFactoryDefault(), RegistrySettings.RegistryQueue, RegisterService);
                serviceRegistryServer.StartInBackground();
                statsConsumer = StartStatsConsumer();

                Console.WriteLine("Registry AMPQ started");
            }

            if (args.Length == 0 || args.Contains("-web"))
            {
                webServer = WebApp.Start<Startup>(url: ServiceConfig.Reader.GetBaseAddress());
                Console.WriteLine("Web server started");
            }
            Console.ReadLine();

            if (statsConsumer != null)
            {
                statsConsumer.StopConsumer();
                serviceRegistryServer.Stop();
            }

            if (webServer != null)
            {
                webServer.Dispose();
            }
        }
		public void TestListen_NotIPv6OnlyOnWinNT6OrLator()
		{
			if ( Environment.OSVersion.Platform != PlatformID.Win32NT || Environment.OSVersion.Version.Major < 6 )
			{
				Assert.Ignore( "This test can be run on WinNT 6 or later." );
			}

			var config = new RpcServerConfiguration() { PreferIPv4 = false };
			using ( var server = new RpcServer() )
			using ( var target = new UdpServerTransportManager( server ) )
			{
				Socket listeningSocket = null;
				target.GetListeningSocket( ref listeningSocket );
				Assert.That( listeningSocket.GetSocketOption( SocketOptionLevel.IPv6, SocketOptionName.IPv6Only ), Is.EqualTo( 0 ) );
			}
		}
		private static void TestSendNotify( int concurrency, Action<IPEndPoint, CountdownEvent, IProducerConsumerCollection<string>> test )
		{
			var endPoint = new IPEndPoint( IPAddress.Loopback, 57319 );
			var config = new RpcServerConfiguration();
			config.BindingEndPoint = endPoint;

			using ( var arrivalLatch = new CountdownEvent( concurrency ) )
			{
				var arriveds = new ConcurrentQueue<string>();
				config.DispatcherProvider =
					s =>
						new CallbackDispatcher(
							s,
							( id, args ) =>
							{
								arriveds.Enqueue( args[ 0 ].ToString() );
								arrivalLatch.Signal();
								return args;
							}
						);
				config.PreferIPv4 = true;

				using ( var server = new RpcServer( config ) )
				using ( var transportManager = new UdpServerTransportManager( server ) )
				{
					test( endPoint, arrivalLatch, arriveds );
				}
			}
		}
Exemplo n.º 55
0
		public void TestBeginShutdown()
		{
			using ( var server = new RpcServer() )
			using ( var target = new Target( server ) )
			{
				target.BeginShutdown();

				Assert.That( target.IsInShutdown, Is.True );
				Assert.That( target.BeginShutdownCalled, Is.True );
			}
		}
Exemplo n.º 56
0
		/// <summary>
		/// Initializes a new instance of the <see cref="CallbackDispatcher"/> class.
		/// </summary>
		/// <param name="server">The server.</param>
		/// <param name="dispatch">The callback with method name.</param>
		public CallbackDispatcher( RpcServer server, Func<string, int?, MessagePackObject[], MessagePackObject> dispatch )
			: base( server )
		{
			this._dispatch = dispatch;
		}
Exemplo n.º 57
0
		/// <summary>
		/// Initializes a new instance of the <see cref="ServerTransportManager"/> class.
		/// </summary>
		/// <param name="server">The server which will host this instance.</param>
		/// <exception cref="ArgumentNullException">
		///		<paramref name="server"/> is <c>null</c>.
		/// </exception>
		protected ServerTransportManager( RpcServer server )
		{
			if ( server == null )
			{
				throw new ArgumentNullException( "server" );
			}

			Contract.EndContractBlock();

			this._requestContextPool = server.Configuration.RequestContextPoolProvider( () => new ServerRequestContext( server.Configuration ), server.Configuration.CreateRequestContextPoolConfiguration() );
			this._responseContextPool = server.Configuration.ResponseContextPoolProvider( () => new ServerResponseContext( server.Configuration ), server.Configuration.CreateResponseContextPoolConfiguration() );

			if ( this._requestContextPool == null )
			{
				throw new InvalidOperationException( "Configuration.RequestContextPoolProvider returns null." );
			}

			if ( this._responseContextPool == null )
			{
				throw new InvalidOperationException( "Configuration.ResponseContextPoolProvider returns null." );
			}

			this._server = server;
		}
Exemplo n.º 58
0
 internal static HandleRef getCPtr(RpcServer obj)
 {
     return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
 }
Exemplo n.º 59
0
		/// <summary>
		/// Initializes a new instance of the <see cref="CallbackDispatcher"/> class.
		/// </summary>
		/// <param name="server">The server.</param>
		/// <param name="callback">The callback without method name.</param>
		public CallbackDispatcher( RpcServer server, Func<int?, MessagePackObject[], MessagePackObject> callback )
			: base( server )
		{
			this._dispatch = ( method, id, args ) => callback( id, args );
		}
		public void TestDispatch_MethodNotExists_NoMethodError()
		{
			using ( var server = new RpcServer() )
			using ( var transportManager = new NullServerTransportManager( server ) )
			using ( var transport = new NullServerTransport( transportManager ) )
			using ( var requestContext = DispatchTestHelper.CreateRequestContext() )
			using ( var argumentsBuffer = new MemoryStream() )
			using ( var waitHandle = new ManualResetEventSlim() )
			{
				var message = Guid.NewGuid().ToString();
				using ( var argumentsPacker = Packer.Create( argumentsBuffer, false ) )
				{
					argumentsPacker.PackArrayHeader( 1 );
					argumentsPacker.Pack( message );
				}

				argumentsBuffer.Position = 0;

				var target = new LocatorBasedDispatcher( server );
				MessagePackObject response = MessagePackObject.Nil;
				requestContext.MethodName = "Echo:TestServices:1";
				requestContext.MessageId = 1;
				requestContext.SetTransport( transport );
				requestContext.ArgumentsUnpacker = Unpacker.Create( argumentsBuffer );
				transport.Sent +=
					( sender, e ) =>
					{
						response = Unpacking.UnpackString( e.Context.GetErrorData() ).Value;
						waitHandle.Set();
					};
				target.Dispatch( transport, requestContext );

				Assert.That( waitHandle.Wait( TimeSpan.FromSeconds( 1 ) ) );

				Assert.That( RpcError.NoMethodError.Identifier == response, "{0} != {1}", message, response );
			}
		}