static void Main(string[] args) { mFactory = new ServerFactory("serverSection"); foreach (IServer item in mFactory.Servers) { Console.WriteLine("{0} start @{1}", item.Name, item.Port); } System.Threading.Thread.Sleep(-1); }
public void SetUp() { acceptor = new AsyncSocketAcceptor(); IKeepAliveMessageFactory factory = new ServerFactory(); KeepAliveFilter filter = new KeepAliveFilter(factory, IdleStatus.BothIdle); acceptor.FilterChain.AddLast("keep-alive", filter); acceptor.DefaultLocalEndPoint = new IPEndPoint(IPAddress.Loopback, 0); acceptor.Bind(); port = ((IPEndPoint)acceptor.LocalEndPoint).Port; }
/// <summary> /// перевод из состояния 60 в состояние 80. Цель - передача песо торговцу. старый вариант /// </summary> public void StateTransferVis2() { Server server; ServerFactory serverFactory; serverFactory = new ServerFactory(this.botwindow); server = serverFactory.create(); // создали конкретный экземпляр класса server по паттерну "простая Фабрика" (Америка, Европа или Синг) if (server.isLogout()) { StateDriverRun(new StateGT060(this.botwindow), new StateGT074(this.botwindow)); } }
public StateGT070(botWindow botwindow) //, GotoTrade gototrade) { this.botwindow = botwindow; this.serverFactory = new ServerFactory(botwindow); this.server = serverFactory.create(); // создали конкретный экземпляр класса server по паттерну "простая Фабрика" (Америка, Европа или Синг) //this.town = server.getTown(); // this.botwindowDealer = new botWindow(20); // здесь методы торговца как у обычного бота this.dealer = new botWindow(20); // здесь уникальные методы, присущие только торговцу this.serverFactory = new ServerFactory(dealer); this.serverDealer = serverFactory.create(); // создали конкретный экземпляр класса server по паттерну "простая Фабрика" (Америка, Европа или Синг) this.tekStateInt = 70; }
public ArraySegment <byte> Encode(object data, IServer server, byte[] buffer) { using (XStream stream = new XStream(server.BufferPool)) { IBinaryWriter writer = ServerFactory.CreateWriter(stream, server.Config.Encoding, server.Config.LittleEndian); OnEncode(data, writer); stream.Position = 0; int count = (int)writer.Length; stream.Read(buffer, 0, count); return(new ArraySegment <byte>(buffer, 0, count)); } }
public static void Main(string[] args) { var cert = new X509Certificate2("server.pfx", "instant"); var serv = ServerFactory.CreateHttp <HttpServ.CGI.CgiAdaptor>(); serv.AddMiddleware <HttpServ.Http2.Middlewares.Http2Handshake>(); serv.AddMiddleware <HttpServ.Http2.Middlewares.PrefaceHandshake>(); serv.AddMiddleware <HttpServ.Http2.Middlewares.Setting>(); serv.AddMiddleware <HttpServ.Http2.Middlewares.PingPong>(); serv.EnableWebSocket(); serv.Open(9916); Console.Read(); }
public UsersInitTests() { _server = ServerFactory.GetServerInstance(); _client = _server.CreateClient(); using (var scope = _server.Host.Services.CreateScope()) { var _db = scope.ServiceProvider.GetRequiredService <LibraryContext>(); _db.User.Add(new User { IdUser = 1, Email = "*****@*****.**", Name = "Daniel", Surname = "Jabłoński", Login = "******", Password = "******" }); _db.User.Add(new User { IdUser = 2, Email = "*****@*****.**", Name = "Daniel2", Surname = "Jabłoński2", Login = "******", Password = "******" }); _db.Book.Add(new Book { IdBook = 1, Title = "HelloWorld", PublishYear = "2020" }); _db.BookBorrow.Add(new BookBorrow { IdBookBorrow = 1, IdUser = 1, IdBook = 1, BorrowDate = DateTime.Now, ReturnDate = DateTime.Now.AddDays(1), Comments = "comment here" }); _db.SaveChanges(); } }
public void ServerWillCloseSocket() { var server = new ServerFactory().Create(call => { throw new InvalidOperationException(); }, 56566); server.Dispose(); Assert.Throws <SocketException>( () => { var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); socket.Connect("localhost", 56566); socket.Close(); }); }
public StateGT086(botWindow botwindow) //, GotoTrade gototrade) { this.botwindow = botwindow; ServerFactory serverFactory = new ServerFactory(botwindow); this.server = serverFactory.create(); // создали конкретный экземпляр класса server по паттерну "простая Фабрика" (Америка, Европа или Синг) OtitFactory otitFactory = new OtitFactory(botwindow); this.otit = otitFactory.createOtit(); DialogFactory dialogFactory = new DialogFactory(botwindow); this.dialog = dialogFactory.createDialog(); this.tekStateInt = 86; }
/// /// <summary>Main for ClosingListener.</summary> /// <param name="args"></param> /// public static void Main(String[] args) { string uri = "tcp://localhost:4001"; /* if (args.Length > 0) * uri = args[0]; */ MainClosingListener implFactory = new MainClosingListener(); ServerFactory listener = ClosingHelper.NewListener(uri, null, implFactory); listener.TransportControl(TransportConsts.START_AND_WAIT_UP, 4000); Console.WriteLine("Listener Started"); }
/// /// <summary>Main for InheritanceListener.</summary> /// <param name="args"></param> /// public static void Main(String[] args) { string uri = "tcp://localhost:4001"; if (args.Length > 0) { uri = args[0]; } MainInheritanceListener implFactory = new MainInheritanceListener(); ServerFactory listener = InheritanceHelper.NewListener(uri, null, implFactory); listener.TransportControl(TransportConsts.START_AND_WAIT_UP, 4000); }
public byte[] Encode(object data, IServer server) { byte[] result = null; using (XStream stream = new XStream(server.BufferPool)) { IBinaryWriter writer = ServerFactory.CreateWriter(stream, server.Config.Encoding, server.Config.LittleEndian); OnEncode(data, writer); stream.Position = 0; result = new byte[stream.Length]; stream.Read(result, 0, result.Length); } return(result); }
static void Main(string[] args) { var serviceProvider = ContainerConfiguration.Configure(); _client = serviceProvider.Resolve <IResponseClient>(); _server = serviceProvider.Resolve <IServer>(); _settings = serviceProvider.Resolve <ISettings>(); var getJson = _settings.getJson(); Console.WriteLine($"Settings: {getJson.Result}"); _settings = JsonConvert.DeserializeObject <Settings>(getJson.Result); int port = args.Length > 0 ? int.Parse(args[0]) : _settings.frontServerPort; string protocol = args.Length > 1 ? args[1] : _settings.defaultProtocol; Console.WriteLine("Server => Running :)"); Console.WriteLine("-------------------"); Console.WriteLine($"Protocol =>{protocol} "); Console.WriteLine("-------------------"); Console.WriteLine($"Port Number =>{port}"); IListener listener = new ServerFactory(port).CreateListener(protocol); var startListener = new Thread(delegate() { _server.ServerStarted(listener); }); startListener.Start(); var startClient = new Thread(delegate() { _client.ServerStarted(listener, _settings.serviceServerPort); }); startClient.Start(); AllocConsole(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(Intervall._form1 = new Form1()); }
public async Task MustReturn401WhenProtectedCustomHeaderIsTampered() { Func <HttpRequestMessage, string, bool> verificationCallback = (request, appSpecificData) => { // Client and server decided that appSpecificData will be // header name:header value, like so: X-Request-Header:Swoosh if (String.IsNullOrEmpty(appSpecificData)) { return(true); // Nothing to check against } var parts = appSpecificData.Split(':'); string headerName = parts[0]; string value = parts[1]; if (request.Headers.Contains(headerName) && request.Headers.GetValues(headerName).First().Equals(value)) { return(true); } return(false); }; server = ServerFactory.Create(null, verificationCallback); using (var invoker = new HttpMessageInvoker(server)) { using (var request = new HttpRequestMessage(HttpMethod.Get, URI)) { // Sensitive header to protect but simulate tampering by changing the value request.Headers.Add("X-Request-Header", "Tampered Swoosh"); var client = new HawkClient(() => ServerFactory.DefaultCredential); // Put the sensitive header in the earlier decided format in the ApplicationSpecificData property client.ApplicationSpecificData = "X-Request-Header:Swoosh"; await client.CreateClientAuthorizationAsync(request); using (var response = await invoker.SendAsync(request, CancellationToken.None)) { Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode); Assert.IsNotNull(response.Headers.WwwAuthenticate.FirstOrDefault()); Assert.AreEqual("hawk", response.Headers.WwwAuthenticate.FirstOrDefault().Scheme); } } } }
protected void submit_Click(object sender, EventArgs e) { char gender = (male.Checked ? 'M' : 'F'); Server server = new Server(firstName.Text, lastName.Text, Convert.ToInt16(age.Text), gender); ServerFactory serverFactory = (ServerFactory)Session["Servers"]; serverFactory.CreateServer(server); updateServerTable(); firstName.Text = ""; lastName.Text = ""; age.Text = ""; male.Checked = false; female.Checked = false; }
public StateGT157(botWindow botwindow) { this.botwindow = botwindow; ServerFactory serverFactory = new ServerFactory(botwindow); this.server = serverFactory.create(); // создали конкретный экземпляр класса server по паттерну "простая Фабрика" (Америка, Европа или Синг) KatoviaMarketFactory marketFactory = new KatoviaMarketFactory(botwindow); this.market = marketFactory.createMarket(); DialogFactory dialogFactory = new DialogFactory(botwindow); this.dialog = dialogFactory.createDialog(); this.tekStateInt = 157; }
static void Main() { System.Console.OutputEncoding = Encoding.UTF8; var factory = new ServerFactory(); var app = factory.CreateServer(System.Console.OpenStandardInput(), System.Console.OpenStandardOutput()); try { app.Listen().Wait(); } catch (AggregateException) { Environment.Exit(-1); } }
public bool Start() { if (IsRunning) { return(false); } var server = new ServerFactory(); host = server.Create(NewServerCallback, Port); IsRunning = true; return(true); }
public ServerTest(ITestOutputHelper output) : base(output) { _output = output; UserStateFactory.ResetId(); _serverPort = BaseServerPort.GetAndIncrement(); _server = ServerFactory.StartWith(World.Stage, Resources, _serverPort, new Configuration.SizingConf(1, 1, 100, 10240), new Configuration.TimingConf(10, 1, 1000)); Assert.True(_server.StartUp().Await(TimeSpan.FromMilliseconds(500L))); _progress = new Progress(); _consumer = World.ActorFor <IResponseChannelConsumer>(() => new TestResponseChannelConsumer(_progress)); _client = new BasicClientRequestResponseChannel(Address.From(Host.Of("localhost"), _serverPort, AddressType.None), _consumer, 100, 10240, World.DefaultLogger); }
/// <summary> /// Registers resources that classes will depend on /// </summary> /// <returns>Task.</returns> protected override async Task RegisterResources() { ServerKernel = new Kernel(ServerConfigurationManager); await base.RegisterResources().ConfigureAwait(false); RegisterSingleInstance <IHttpResultFactory>(new HttpResultFactory(LogManager)); RegisterSingleInstance <IServerApplicationHost>(this); RegisterSingleInstance <IServerApplicationPaths>(ApplicationPaths); RegisterSingleInstance(ServerKernel); RegisterSingleInstance(ServerConfigurationManager); RegisterSingleInstance <IWebSocketServer>(() => new AlchemyServer(Logger)); RegisterSingleInstance <IIsoManager>(new PismoIsoManager(Logger)); RegisterSingleInstance <IBlurayExaminer>(new BdInfoExaminer()); ZipClient = new DotNetZipClient(); RegisterSingleInstance(ZipClient); HttpServer = ServerFactory.CreateServer(this, ProtobufSerializer, Logger, "Media Browser", "index.html"); RegisterSingleInstance(HttpServer, false); ServerManager = new ServerManager(this, JsonSerializer, Logger, ServerConfigurationManager, ServerKernel); RegisterSingleInstance(ServerManager); UserManager = new UserManager(ServerKernel, Logger, ServerConfigurationManager); RegisterSingleInstance(UserManager); LibraryManager = new LibraryManager(ServerKernel, Logger, TaskManager, UserManager, ServerConfigurationManager); RegisterSingleInstance(LibraryManager); InstallationManager = new InstallationManager(HttpClient, PackageManager, JsonSerializer, Logger, this); RegisterSingleInstance(InstallationManager); DirectoryWatchers = new DirectoryWatchers(LogManager, TaskManager, LibraryManager, ServerConfigurationManager); RegisterSingleInstance(DirectoryWatchers); ProviderManager = new ProviderManager(HttpClient, ServerConfigurationManager, DirectoryWatchers, LogManager); RegisterSingleInstance(ProviderManager); RegisterSingleInstance <ILibrarySearchEngine>(() => new LuceneSearchEngine()); SetKernelProperties(); SetStaticProperties(); }
private void Start() { UInt16 port = Convert.ToUInt16(_portTextBox.Text); if (_server == null) { if (!String.IsNullOrEmpty(_configFile)) { _serverConfig = TcpServerConfigBuilder.Build(_configFile); } if (!String.IsNullOrEmpty(_compilerOptionsFile)) { _compilerOptions = CompilerOptionsBuilder.Build(_compilerOptionsFile); } if (_ipAddressComboBox.SelectedIndex >= 0 && _portTextBox.Text != null && !String.IsNullOrEmpty(_scriptFile)) { _server = ServerFactory.Create(_ipAddressComboBox.Items[_ipAddressComboBox.SelectedIndex].ToString(), port, _scriptFile, _logger, _compilerOptions, _serverConfig); } else { MessageBox.Show(@"Can not start server, please select IP address, port and server script"); return; } _server.Start(); } else { if (!String.IsNullOrEmpty(_compilerOptionsFile)) { _compilerOptions = CompilerOptionsBuilder.Build(_compilerOptionsFile); } if (_configChanged) { _server = ServerFactory.Create(_ipAddressComboBox.Items[_ipAddressComboBox.SelectedIndex].ToString(), port, _scriptFile, _logger, _compilerOptions, _serverConfig); } _server.Start(_ipAddressComboBox.Items[_ipAddressComboBox.SelectedIndex].ToString(), port); } if (_timers[0] == null) { System.Threading.Timer periodicalUpdater = new System.Threading.Timer(StateUpdater, null, 500, 500); _timers[0] = periodicalUpdater; } else { _timers[0].Change(500, 500); } }
private protected async Task RequestResponseTest(ServerFactory serverFactory, ClientFactory clientFactory) { var timeout = TimeSpan.FromSeconds(20); //prepare server var serverAddr = new IPEndPoint(IPAddress.Loopback, 3789); using var server = serverFactory(new LocalMember(), serverAddr, timeout); server.Start(); //prepare client using var client = clientFactory(serverAddr); //Vote request CancellationTokenSource timeoutTokenSource; Result <bool> result; using (timeoutTokenSource = new CancellationTokenSource(timeout)) { var exchange = new VoteExchange(42L, 1L, 56L); client.Enqueue(exchange, timeoutTokenSource.Token); result = await exchange.Task; True(result.Value); Equal(43L, result.Term); } // PreVote reqyest using (timeoutTokenSource = new CancellationTokenSource(timeout)) { var exchange = new PreVoteExchange(10L, 2L, 99L); client.Enqueue(exchange, timeoutTokenSource.Token); result = await exchange.Task; True(result.Value); Equal(44L, result.Term); } //Resign request using (timeoutTokenSource = new CancellationTokenSource(timeout)) { var exchange = new ResignExchange(); client.Enqueue(exchange, timeoutTokenSource.Token); True(await exchange.Task); } //Heartbeat request using (timeoutTokenSource = new CancellationTokenSource(timeout)) { var exchange = new HeartbeatExchange(42L, 1L, 56L, 10L); client.Enqueue(exchange, timeoutTokenSource.Token); result = await exchange.Task; True(result.Value); Equal(43L, result.Term); } }
/// <summary> /// Setup the TCP socket server. /// </summary> private void SetupTCP() { TCPServer = ServerFactory <Habbo> .CreateServer(GameSettings.Instance.GamePort); TCPServer.OnConnectionOpened += ClientManager.AddClient; // TODO: Connection security! TCPServer.OnConnectionClosed += ClientManager.RemoveClient; TCPServer.OnMessageReceived += (ISession <Habbo> session, byte[] body) => { // using(global::Yupi.Emulator.Messages.Buffers.SimpleClientMessageBuffer message = ClientMessageFactory.GetClientMessage()) { // TODO: When using message pool the SimpleClientMessageBuffer becomes invalid (after several messages) -> DEBUG ClientMessage message = new ClientMessage(); message.Setup(body); Router.Default.Handle(session.UserData, message); }; }
protected override void OnStart(string[] args) { try { mFactory = new ServerFactory("serverSection"); foreach (IServer item in mFactory.Servers) { Utils.GetLog<SNServiceApp>().InfoFormat("{0} start @{1}", item.Name, item.Port); } Utils.GetLog<SNServiceApp>().InfoFormat("SN Server Started!"); } catch (Exception e_) { Utils.GetLog<SNServiceApp>().ErrorFormat("SN Server start error {0}", e_.Message); } }
static void Main(string[] args) { var app = new AppBuilder(); app.Properties["host.Addresses"] = HostAddresses; ServerFactory.Initialize(app); Startup.Configuration(app); var server = ServerFactory.Create(app.Build(), app.Properties); System.Console.WriteLine("Running on http://localhost:8080/"); System.Console.WriteLine("Press enter to exit"); System.Console.ReadLine(); server.Dispose(); }
protected override void OnStart(string[] args) { try { mFactory = new ServerFactory("serverSection"); foreach (IServer item in mFactory.Servers) { Utils.GetLog <SNServiceApp>().InfoFormat("{0} start @{1}", item.Name, item.Port); } Utils.GetLog <SNServiceApp>().InfoFormat("SN Server Started!"); } catch (Exception e_) { Utils.GetLog <SNServiceApp>().ErrorFormat("SN Server start error {0}", e_.Message); } }
///<summary>Main for IOTListener.</summary> ///<param name="args">Command Line Arguments</param> public static void Main(String[] args) { if (args.Length > 1) { Console.WriteLine("usage: MainIOTListener [uri]"); return; } string uri = args.Length > 0 ? args[0] : "tcp://localhost:4001"; ServerFactory listener = IOTHelper.NewListener(uri, null, new MainIOTListener()); // Start the Listener listener.TransportControl(TransportConsts.START_AND_WAIT_UP, 4000); Console.WriteLine("listener started: " + listener); }
public async Task UseGraphQLHttpGet_BuilderServices() { // arrange TestServer server = ServerFactory.Create( services => services.AddStarWars(), (app, sp) => app.UseGraphQLHttpGet(sp)); // act HttpResponseMessage message = await server.SendGetRequestAsync("{ hero { name } }"); // assert ClientQueryResult result = await DeserializeAsync(message); result.MatchSnapshot(); }
public static void Main(string[] args) { BeetleX.Clients.IClient client = ServerFactory.CreateTcpClient("127.0.0.1", 9090); client.Receive = (c, e) => { lock (e.SyncObject) { Console.WriteLine(e.ReadLine()); } }; client.Connect(); client.Writer.WriteLine(DateTime.Now.ToString()); client.Writer.Flush(); Console.Read(); }
public ZeusServerBase(string address) { // Minimal address content validation if (string.IsNullOrEmpty(address)) { throw new ArgumentNullException("address"); } // Create end-point and server _endPoint = new TcpEndPoint(address); _server = ServerFactory.CreateServer(_endPoint); // Attach client events _server.ClientConnected += ServerOnClientConnected; _server.ClientDisconnected += ServerOnClientDisconnected; }
private protected async Task MetadataRequestResponseTest(ServerFactory serverFactory, ClientFactory clientFactory, bool smallAmountOfMetadata) { var timeout = TimeSpan.FromSeconds(20); //prepare server var member = new LocalMember(smallAmountOfMetadata); var serverAddr = new IPEndPoint(IPAddress.Loopback, 3789); using var server = serverFactory(member, serverAddr, timeout); server.Start(); //prepare client using var client = clientFactory(serverAddr); var exchange = new MetadataExchange(CancellationToken.None); client.Enqueue(exchange, default); Equal(member.Metadata, await exchange.Task); }
public StateGT253(botWindow botwindow) //, GotoTrade gototrade) { this.botwindow = botwindow; ServerFactory serverFactory = new ServerFactory(botwindow); this.server = serverFactory.create(); // создали конкретный экземпляр класса server по паттерну "простая Фабрика" (Америка, Европа или Синг) this.town = server.getTown(); DialogFactory dialogFactory = new DialogFactory(botwindow); dialog = dialogFactory.createDialog(); this.tekStateInt = 253; //this.resultat = true; }
public static void Main(string[] args) { SearchEmployee search; DefaultClientPacket.Register(typeof(Program)); IClient client = ServerFactory.CreateTcpClient <DefaultClientPacket>("127.0.0.1", 9090); client.Packet.Completed = OnReceive; client.ClientError = (c, e, m) => { Console.WriteLine(m); }; search = new SearchEmployee(); search.Size = 1; client.Send(search); Console.Read(); }
static void Main(string[] args) { System.Threading.ThreadPool.SetMaxThreads(20, 20); System.Threading.ThreadPool.SetMinThreads(20, 20); try { mFactory = new ServerFactory("serverSection"); foreach (IServer item in mFactory.Servers) { Utils.GetLog<Program>().InfoFormat("{0} start @{1}", item.Name, item.Port); } Utils.GetLog<Program>().InfoFormat("SN Server Started!"); } catch (Exception e_) { Utils.GetLog<Program>().ErrorFormat("SN Server start error {0}", e_.Message); } System.Threading.Thread.Sleep(-1); }
public MultiClientServer(ServerFactory tFactory, TcpListener listener) { this.tFactory = tFactory; this.listener = listener; }