示例#1
0
        public int Start(int pingInterval = 3, int requestTimeout = 4)
        {
            Random rnd = new Random();

            for (int i = 0; i < 50; i++)
            {
                try
                {
                    int           port          = rnd.Next(5000, 65000);
                    ServerOptions serverOptions = ServerOptions.CreateDefault();
                    serverOptions.Hosts[0].Port  = port;
                    serverOptions.PingInterval   = pingInterval;
                    serverOptions.RequestTimeout = requestTimeout;

                    HorseServer server = new HorseServer(serverOptions);
                    server.UseHorseMq(Server);
                    server.Start();
                    Port = port;
                    return(port);
                }
                catch
                {
                    Thread.Sleep(2);
                }
            }

            return(0);
        }
        public void Start(int port)
        {
            HorseServer server = new HorseServer(ServerOptions.CreateDefault());

            server.UseWebSockets(async delegate { await Task.CompletedTask; });
            server.Start(port);
        }
示例#3
0
        /// <summary>
        /// Starts new server, connects to remote node clients and starts to listen incoming node connections
        /// </summary>
        public async Task Start()
        {
            foreach (HmqStickyConnector connector in Connectors)
            {
                connector.Run();
            }

            if (_nodeServer != null && _nodeServer.IsRunning)
            {
                _nodeServer.Stop();
                _nodeServer = null;
                await Task.Delay(500);
            }

            if (Server.Options.NodeHost == null)
            {
                return;
            }

            _nodeServer = new HorseServer(new ServerOptions
            {
                Hosts = new List <HostOptions> {
                    Server.Options.NodeHost
                },
                PingInterval   = 15,
                RequestTimeout = 15
            });

            _nodeServer.Start();
        }
示例#4
0
        public void Run()
        {
            HorseMvc mvc = new HorseMvc();

            HomeController cont = new HomeController();

            Assert.NotNull(cont);

            mvc.Init();
            Assembly asm = Assembly.GetExecutingAssembly();

            mvc.CreateRoutes(asm);
            mvc.Use();

            HorseServer server = new HorseServer(ServerOptions.CreateDefault());

            server.UseMvc(mvc, HttpOptions.CreateDefault());
            server.Start(47442);
            System.Threading.Thread.Sleep(1000);

            HttpClient          client   = new HttpClient();
            HttpResponseMessage response = client.GetAsync("http://127.0.0.1:47442/home/get").Result;

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        }
示例#5
0
        private static void Main(string[] args)
        {
            HorseMq mq = HorseMqBuilder.Create()
                         .AddClientHandler <ClientHandler>()
                         .AddQueueEventHandler <QueueEventHandler>()
                         .UseJustAllowDeliveryHandler()
                         .Build();

            var sampleMessageRouter        = mq.AddRouter("SAMPLE-MESSAGE-ROUTER", RouteMethod.Distribute);
            var sampleMessageQueueBinding  = new QueueBinding("sample-message-queue-binding", "SAMPLE-MESSAGE-QUEUE", 1, BindingInteraction.Response);
            var sampleMessageDirectBinding = new DirectBinding("sample-message-direct-binding", "@type:SAMPLE-MESSAGE-CONSUMER", 2, BindingInteraction.Response, RouteMethod.RoundRobin);

            sampleMessageRouter.AddBinding(sampleMessageQueueBinding);
            sampleMessageRouter.AddBinding(sampleMessageDirectBinding);

            var giveMeGuidRequestRouter  = mq.AddRouter("GIVE-ME-REQUEST-ROUTER", RouteMethod.Distribute);
            var giveMeGuidRequestHandler = new DirectBinding("sample-message-direct-binding", "@name:GIVE-ME-GUID-REQUEST-HANDLER-CONSUMER", 2, BindingInteraction.Response);

            giveMeGuidRequestRouter.AddBinding(giveMeGuidRequestHandler);

            HorseServer server = new HorseServer();

            server.UseHorseMq(mq);
            server.Run(15500);
        }
示例#6
0
        static void Main(string[] args)
        {
            HorseMvc mvc = new HorseMvc();
            HorseServer
                server = new HorseServer();

            mvc.Init();
            server.UseMvc(mvc, HttpOptions.CreateDefault());
            server.Run();
        }
示例#7
0
 public AbsoluteConnectorTest()
 {
     _server = new HorseServer(ServerOptions.CreateDefault());
     _server.UseWebSockets(async(socket) => { await socket.SendAsync("Welcome"); },
                           async(socket, message) =>
     {
         _receivedMessages++;
         await Task.CompletedTask;
     });
 }
示例#8
0
        /// <summary>
        /// Stop node server, disconnects from remote node servers and stops to listen incoming node client connections
        /// </summary>
        public void Stop()
        {
            foreach (HmqStickyConnector connector in Connectors)
            {
                connector.Abort();
            }

            if (_nodeServer != null)
            {
                _nodeServer.Stop();
                _nodeServer = null;
            }
        }
示例#9
0
        static void Main(string[] args)
        {
            HorseMvc mvc = new HorseMvc();

            mvc.IsDevelopment = false;
            mvc.Init(services =>
            {
                services.AddScoped <IScopedService, ScopedService>();
                services.AddTransient <IFirstService, FirstService>();
                services.AddTransient <ISecondService, SecondService>();

                services.AddJwt(mvc, options =>
                {
                    options.Key              = "Very_very_secret_key";
                    options.Issuer           = "localhost";
                    options.Audience         = "localhost";
                    options.Lifetime         = TimeSpan.FromHours(1);
                    options.ValidateAudience = false;
                    options.ValidateIssuer   = false;
                    options.ValidateLifetime = true;
                });

                mvc.Policies.Add(Policy.RequireRole("Admin", "Admin"));
                mvc.Policies.Add(Policy.RequireClaims("IT", "Database", "Cloud", "Source"));
                mvc.Policies.Add(Policy.Custom("Custom", (d, c) => true));

                mvc.StatusCodeResults.Add(HttpStatusCode.Unauthorized, new JsonResult(new { Message = "Access denied" }));

                mvc.ErrorHandler = new MvcErrorHandler();
            });

            CorsMiddleware cors = new CorsMiddleware();

            cors.AllowAll();

            mvc.Use(app =>
            {
                app.UseActionRoute("/test-action", request => new StringResult("Hello, Test Action!"));

                app.UseMiddleware(cors);
                app.UseMiddleware <TMid>();
                app.UseFiles("/download", "/home/mehmet/files");
            });

            HorseServer server = new HorseServer();
            var         opt    = HttpOptions.CreateDefault();

            opt.HttpConnectionTimeMax = 0;
            server.UseMvc(mvc, opt);
            server.Run(4410);
        }
示例#10
0
        static void Main(string[] args)
        {
            IServiceCollection services = new ServiceCollection();
            HorseServer        server   = new HorseServer();

            server.AddWebSockets(cfg => cfg.AddBus(services)
                                 //.UsePipeModelProvider(new NewtonsoftJsonModelSerializer())
                                 .UsePayloadModelProvider(new SystemJsonModelSerializer())
                                 .AddSingletonHandlers(typeof(Program))

                                 /*
                                  * .OnClientConnected((info, data) =>
                                  * {
                                  *  WsServerSocket socket = new YourDerivedCustomSocket(info, data);
                                  *  Task.FromResult(socket);
                                  * })
                                  */
                                 .OnClientReady(client =>
            {
                Console.WriteLine("Client connected");
                return(Task.CompletedTask);
            })
                                 .OnClientDisconnected(client =>
            {
                Console.WriteLine("Client disconnected");
                return(Task.CompletedTask);
            })
                                 .OnError(exception => Console.WriteLine("Error: " + exception)));

            server.UseWebSockets(services.BuildServiceProvider());

            server.UseHttp((request, response) =>
            {
                if (request.Path.Equals("/status", StringComparison.InvariantCultureIgnoreCase))
                {
                    response.SetToText();
                    response.StatusCode = HttpStatusCode.OK;
                    response.Write("OK");
                }
                else
                {
                    response.StatusCode = HttpStatusCode.NotFound;
                }

                return(Task.CompletedTask);
            });

            server.Run(26111);
        }
示例#11
0
        /// <summary>
        /// Uses Horse.Mq Messaging Queue server
        /// </summary>
        public static HorseServer UseHorseMq(this HorseServer server, HorseMq horseMq)
        {
            HmqNetworkHandler handler = new HmqNetworkHandler(horseMq);

            horseMq.Server = server;

            horseMq.NodeManager.ConnectionHandler = new NodeConnectionHandler(horseMq.NodeManager, handler);
            server.UseHmq(handler);

            if (horseMq.NodeManager != null)
            {
                horseMq.NodeManager.SubscribeStartStop(server);
            }

            return(server);
        }
示例#12
0
        static void Main(string[] args)
        {
            HorseServer server = new HorseServer();

            HorseMvc mvc = new HorseMvc();

            mvc.Init(services => { });

            mvc.Use(app =>
            {
                IServiceProvider provider = app.GetProvider();
            });

            server.UseMvc(mvc);
            server.Run(5000);
        }
示例#13
0
        /// <summary>
        /// Subscribes start and stop events of server
        /// </summary>
        internal void SubscribeStartStop(HorseServer server)
        {
            if (_subscribed)
            {
                return;
            }

            _subscribed = true;

            server.OnStarted += s => _ = Start();
            server.OnStopped += s => Stop();

            if (server.IsRunning)
            {
                _ = Start();
            }
        }
示例#14
0
        static void Main(string[] args)
        {
            HorseMq mq = HorseMqBuilder.Create()
                         .AddOptions(o => o.Status = QueueStatus.Push)
                         .AddClientHandler <ClientHandler>()
                         .AddQueueEventHandler <QueueEventHandler>()
                         .AddPersistentQueues()
                         .UsePersistentDeliveryHandler(DeleteWhen.AfterAcknowledgeReceived, ProducerAckDecision.AfterSaved)
                         .Build();

            mq.LoadPersistentQueues();

            HorseServer server = new HorseServer();

            server.UseHorseMq(mq);
            server.Run(26222);
        }
示例#15
0
        static void Main(string[] args)
        {
            HorseServer server = new HorseServer(ServerOptions.CreateDefault());

            server.UseHttp((request, response) =>
            {
                if (request.Path.Equals("/plaintext", StringComparison.InvariantCultureIgnoreCase))
                {
                    response.SetToText();
                    return(response.WriteAsync("Hello, World!"));
                }

                response.StatusCode = HttpStatusCode.NotFound;
                return(Task.CompletedTask);
            }, HttpOptions.CreateDefault());

            server.Run(5000);
        }
示例#16
0
        static void StartServer()
        {
            HorseServer server = new HorseServer(ServerOptions.CreateDefault());

            server.UseWebSockets(async(socket, data) =>
            {
                Console.WriteLine("connected");
                socket.Disconnected += c => Console.WriteLine("disconnected");
                await Task.CompletedTask;
            },
                                 async(socket, message) =>
            {
                Console.Write(message);
                await socket.SendAsync(message);
            });

            server.Options.PingInterval = 30;
            server.Start();
        }
示例#17
0
        static void Main(string[] args)
        {
            HorseServer server = new HorseServer(ServerOptions.CreateDefault());

            server.UseHttp(async(request, response) =>
            {
                if (request.Path.Equals("/plaintext", StringComparison.InvariantCultureIgnoreCase))
                {
                    response.SetToText();
                    await response.WriteAsync("Hello, World!");
                }
                else
                {
                    response.StatusCode = HttpStatusCode.NotFound;
                }
            });

            server.Run(22);
        }
示例#18
0
        static void Main(string[] args)
        {
            HorseServer server = new HorseServer(ServerOptions.CreateDefault());

            server.UseHttp(async(request, response) =>
            {
                if (request.Path.Equals("/json", StringComparison.InvariantCultureIgnoreCase))
                {
                    response.SetToJson(new { message = "Hello, World!" });
                }
                else
                {
                    response.StatusCode = HttpStatusCode.NotFound;
                }

                await Task.CompletedTask;
            }, HttpOptions.CreateDefault());

            server.Run();
        }
示例#19
0
        /// <summary>
        /// Uses Horse.Mq Messaging Queue server
        /// </summary>
        public static HorseMq UseHorseMq(this HorseServer server, Action <HorseMqBuilder> cfg)
        {
            HorseMq           mq      = new HorseMq();
            HmqNetworkHandler handler = new HmqNetworkHandler(mq);

            mq.Server = server;

            mq.NodeManager.ConnectionHandler = new NodeConnectionHandler(mq.NodeManager, handler);
            server.UseHmq(handler);

            if (mq.NodeManager != null)
            {
                mq.NodeManager.SubscribeStartStop(server);
            }

            HorseMqBuilder builder = new HorseMqBuilder();

            builder.Server = mq;

            cfg(builder);
            return(mq);
        }
示例#20
0
        static void Main(string[] args)
        {
            ServerWsHandler handler = new ServerWsHandler();
            HorseServer     server  = new HorseServer(new ServerOptions
            {
                PingInterval = 15,
                Hosts        = new List <HostOptions>
                {
                    new HostOptions
                    {
                        Port = 4083
                    }
                }
            });

            server.UseWebSockets(handler);
            server.Start();

            while (true)
            {
                Console.ReadLine();
                Console.WriteLine(handler.Online + " Online");
            }
        }
示例#21
0
        public async Task ReloadAfterRestart()
        {
            await Task.Delay(500);

            ConfigurationFactory.Destroy();
            RedeliveryService service = new RedeliveryService("data/reload-test.tdb.delivery");
            await service.Load();

            await service.Clear();

            await service.Set("id", 4);

            await service.Close();

            if (System.IO.File.Exists("data/config.json"))
            {
                System.IO.File.Delete("data/config.json");
            }

            if (System.IO.File.Exists("data/reload-test.tdb"))
            {
                System.IO.File.Delete("data/reload-test.tdb");
            }

            if (System.IO.File.Exists("data/reload-test.tdb.delivery"))
            {
                System.IO.File.Delete("data/reload-test.tdb.delivery");
            }

            HorseServer server = new HorseServer();
            PersistentDeliveryHandler handler = null;
            Func <DeliveryHandlerBuilder, Task <IMessageDeliveryHandler> > fac = async builder =>
            {
                DatabaseOptions options = new DatabaseOptions
                {
                    Filename             = "data/reload-test.tdb",
                    InstantFlush         = true,
                    CreateBackupOnShrink = false,
                    ShrinkInterval       = TimeSpan.FromSeconds(60)
                };

                handler = (PersistentDeliveryHandler)await builder.CreatePersistentDeliveryHandler(o =>
                {
                    return(new PersistentDeliveryHandler(builder.Queue,
                                                         options,
                                                         DeleteWhen.AfterSend,
                                                         ProducerAckDecision.None,
                                                         true));
                });

                return(handler);
            };

            HorseMq mq = server.UseHorseMq(cfg => cfg
                                           .AddPersistentQueues(q => q.KeepLastBackup())
                                           .UseDeliveryHandler(fac));

            HorseQueue queue = await mq.CreateQueue("reload-test",
                                                    o => o.Status = QueueStatus.Push);

            HorseMessage msg = new HorseMessage(MessageType.QueueMessage, "reload-test");

            msg.SetMessageId("id");
            msg.SetStringContent("Hello, World!");
            await queue.Push(msg);

            QueueMessage queueMsg = queue.Messages.FirstOrDefault();
            await handler.BeginSend(queue, queueMsg);

            await handler.RedeliveryService.Close();

            ConfigurationFactory.Destroy();

            mq = server.UseHorseMq(cfg => cfg
                                   .AddPersistentQueues(q => q.KeepLastBackup())
                                   .UseDeliveryHandler(fac));

            await mq.LoadPersistentQueues();

            HorseQueue queue2 = mq.FindQueue("reload-test");

            Assert.NotNull(queue2);
            Assert.NotEmpty(queue2.Messages);
            QueueMessage loadedMsg = queue2.Messages.FirstOrDefault();

            Assert.NotNull(loadedMsg);
            Assert.Equal(1, loadedMsg.DeliveryCount);
        }
示例#22
0
        public async Task InPersistentHandler()
        {
            ConfigurationFactory.Destroy();
            PersistentDeliveryHandler handler = null;
            HorseServer server = new HorseServer();
            HorseMq     mq     = server.UseHorseMq(cfg => cfg
                                                   .AddPersistentQueues(q => q.KeepLastBackup())
                                                   .UseDeliveryHandler(async builder =>
            {
                DatabaseOptions options = new DatabaseOptions
                {
                    Filename             = "redelivery-test.tdb",
                    InstantFlush         = true,
                    CreateBackupOnShrink = false,
                    ShrinkInterval       = TimeSpan.FromSeconds(60)
                };

                handler = new PersistentDeliveryHandler(builder.Queue,
                                                        options,
                                                        DeleteWhen.AfterSend,
                                                        ProducerAckDecision.None,
                                                        true);
                await handler.Initialize();
                return(handler);
            }));

            HorseQueue queue = await mq.CreateQueue("test");

            HorseMessage message = new HorseMessage(MessageType.QueueMessage, "test");

            message.SetMessageId("id");
            message.SetStringContent("Hello, World!");
            QueueMessage queueMessage = new QueueMessage(message);

            await handler.BeginSend(queue, queueMessage);

            List <KeyValuePair <string, int> > deliveries = handler.RedeliveryService.GetDeliveries();

            Assert.Single(deliveries);
            Assert.Equal("id", deliveries[0].Key);
            Assert.Equal(1, deliveries[0].Value);

            string header = message.FindHeader(HorseHeaders.DELIVERY);

            Assert.Null(header);

            await handler.BeginSend(queue, queueMessage);

            deliveries = handler.RedeliveryService.GetDeliveries();
            Assert.Single(deliveries);
            Assert.Equal("id", deliveries[0].Key);
            Assert.Equal(2, deliveries[0].Value);

            header = message.FindHeader(HorseHeaders.DELIVERY);
            Assert.NotNull(header);
            Assert.Equal(2, Convert.ToInt32(header));

            queueMessage.MarkAsSent();

            await handler.EndSend(queue, queueMessage);

            deliveries = handler.RedeliveryService.GetDeliveries();
            Assert.Empty(deliveries);
        }