Exemple #1
0
 public DispatchLoop(TcpListener listener, ILogger logger, 
                   IProtocolFactory protoFactory)
 {
     this.listener     = listener;
     this.logger       = logger;
     this.protoFactory = protoFactory;
 }
        public void RegisterProtocol(IProtocolFactory factory)
        {
            IInternetSession session = null;
              if (NativeMethods.CoInternetGetSession (0, ref session, 0) != 0)
            return;

              var id = GuidFromType (factory.ProtocolType);
              session.RegisterNameSpace (factory, ref id, factory.ProtocolName, 0, null, 0);
        }
        void IPeerConnector.Bind(IReactor dispatcher, IProtocolFactory factory, IPEndPoint localEP, IPEndPoint remoteEP, int bufferSize)
        {
            _factory = factory;
            _dispatcher = dispatcher;
            _bufferSize = bufferSize;

            var tcpClient = new TcpClient(localEP);
            var ar = tcpClient.BeginConnect(remoteEP.Address, remoteEP.Port, null, tcpClient);
            _dispatcher.AddResult(ar, (iar, state) => { this.PeerConnectCallback(iar); }, tcpClient);
        }
        public void Connect(IProtocolFactory factory, IPEndPoint peer)
        {
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _factory = factory;

            _factory.StartedConnecting();

            IAsyncResult result = _socket.BeginConnect(peer, null, null);

            _reactor.AddResult(result, ConnectCompleted);
        }
Exemple #5
0
 public void startDispatching(TcpListener listener, ILogger logger,
                            IProtocolFactory protoFactory)
 {
     // Create N threads, each running an iterative server
     for (int i = 0; i < numThreads; i++) {
       DispatchLoop dl = new DispatchLoop(listener, logger, protoFactory);
       Thread thread = new Thread(new ThreadStart(dl.rundispatcher));
       thread.Start();
       logger.writeEntry("Created and started Thread = " + thread.GetHashCode());
     }
 }
Exemple #6
0
        void IConnector.Bind(IReactor dispatcher, IProtocolFactory factory, IPEndPoint localEP, int bufferSize)
        {
            _factory = factory;
            _dispatcher = dispatcher;
            _bufferSize = bufferSize;

            _tcpListener = new TcpListener(localEP);
            _tcpListener.Start();

            this.StartAccept();
        }
        void IConnector.Bind(IReactor dispatcher, IProtocolFactory factory, IPEndPoint localEP, int bufferSize)
        {
            _udpClient = new UdpClient(localEP);
            _udpClient.Client.ReceiveBufferSize = bufferSize;

            var protocol = factory.Create();

            var connection = new DatagramConnection(dispatcher, protocol, _udpClient);
            connection.Start(true);

            protocol.Bind(connection);
            protocol.Connected();
        }
Exemple #8
0
        internal void RunEchoBenchmark(int clients, int iterations, IProtocolFactory factory, TextWriter log)
        {
            Thread[] threads = new Thread[clients];
            int remaining = clients;
            ManualResetEvent evt = new ManualResetEvent(false);
            Stopwatch watch = new Stopwatch();
            long opsPerSecond;
            //ThreadStart work = () => RunEchoClient(iterations, ref remaining, evt, watch, factory);

            //for (int i = 0; i < clients; i++)
            //{
            //    threads[i] = new Thread(work);
            //}

            //for (int i = 0; i < clients; i++)
            //{
            //    threads[i].Start();
            //}
            //for (int i = 0; i < clients; i++)
            //{
            //    threads[i].Join();
            //}
            //watch.Stop();
            //opsPerSecond = watch.ElapsedMilliseconds == 0 ? -1 : (clients * iterations * 1000) / watch.ElapsedMilliseconds;
            //log?.WriteLine("Total elapsed: {0}ms, {1}ops/s (individual clients)", watch.ElapsedMilliseconds, opsPerSecond);


            var endpoints = Enumerable.Repeat(new IPEndPoint(IPAddress.Loopback, 5999), clients).ToArray();
            var tasks = new Task[iterations];
            byte[] message = new byte[1000];
            new Random(123456).NextBytes(message);
            using(var clientGroup = new TcpClientGroup())
            {
                clientGroup.MaxIncomingQuota = -1;
                clientGroup.ProtocolFactory = factory;
                clientGroup.Open(endpoints);
                watch = Stopwatch.StartNew();
                
                for(int i = 0 ; i < iterations ; i++)
                {
                    tasks[i] = clientGroup.Execute(message);
                }
                Task.WaitAll(tasks);
                watch.Stop();
            }
            opsPerSecond = watch.ElapsedMilliseconds == 0 ? -1 : (iterations * 1000) / watch.ElapsedMilliseconds;
            log?.WriteLine("Total elapsed: {0}ms, {1}ops/s (grouped clients)", watch.ElapsedMilliseconds, opsPerSecond);


        }
Exemple #9
0
        public TcpService(string configuration, IMessageProcessor processor, IProtocolFactory factory)
        {
            if (processor == null)
            {
                throw new ArgumentNullException("processor");
            }
            this.processor = processor;
            this.factory   = factory;
            Configuration  = configuration;
            ServiceName    = processor.Name;

            MaxIncomingQuota = TcpHandler.DefaultMaxIncomingQuota;
            MaxOutgoingQuota = TcpHandler.DefaultMaxOutgoingQuota;
        }
Exemple #10
0
 public GlobalPKAnalysisTask(IParameterFactory parameterFactory, IProtocolToSchemaItemsMapper protocolToSchemaItemsMapper,
                             IProtocolFactory protocolFactory, IGlobalPKAnalysisRunner globalPKAnalysisRunner, IPKAnalysesTask pkAnalysesTask,
                             IPKCalculationOptionsFactory pkCalculationOptionsFactory, IVSSCalculator vssCalculator, IInteractionTask interactionTask, ICloner cloner)
 {
     _parameterFactory            = parameterFactory;
     _protocolToSchemaItemsMapper = protocolToSchemaItemsMapper;
     _protocolFactory             = protocolFactory;
     _globalPKAnalysisRunner      = globalPKAnalysisRunner;
     _pkAnalysisTask = pkAnalysesTask;
     _pkCalculationOptionsFactory = pkCalculationOptionsFactory;
     _vssCalculator   = vssCalculator;
     _interactionTask = interactionTask;
     _cloner          = cloner;
 }
Exemple #11
0
        void IConnector.Bind(IReactor dispatcher, IProtocolFactory factory, IPEndPoint localEP, int bufferSize)
        {
            _udpClient = new UdpClient(localEP);
            _udpClient.Client.ReceiveBufferSize = bufferSize;

            var protocol = factory.Create();

            var connection = new DatagramConnection(dispatcher, protocol, _udpClient);

            connection.Start(true);

            protocol.Bind(connection);
            protocol.Connected();
        }
Exemple #12
0
        /// <summary>
        /// Register a new APP for the application.
        /// </summary>
        /// <param name="protocol">the protocol (for instance "http")</param>
        /// <param name="factory">the IProtocolFactory used to build the protocol handler</param>
        public static void Register(string protocol, IProtocolFactory factory)
        {
            Guid guid = Guid.Empty;

            //internetSession.RegisterNameSpace(new ClassFactory(), ref guid, "http", 0,null, 0);

            if (_currentProtocolHandler[protocol] != null)
            {
                Unregister(protocol);
            }
            ClassFactory f = new ClassFactory(factory);

            _currentProtocolHandler[protocol] = f;
            internetSession.RegisterNameSpace(f, ref guid, protocol, 0, null, 0);
        }
 public CreateProtocolPresenter(ICreateProtocolView view,
                                ISubPresenterItemManager <IProtocolItemPresenter> subPresenterItemManager,
                                IBuildingBlockPropertiesMapper propertiesMapper,
                                IProtocolChartPresenter protocolChartPresenter,
                                IProtocolFactory protocolFactory,
                                IProtocolUpdater protocolUpdater,
                                IProtocolToProtocolPropertiesDTOMapper protocolPropertiesDTOMapper, IDialogCreator dialogCreator)
     : base(view, subPresenterItemManager, ProtocolItems.All, dialogCreator)
 {
     _propertiesMapper            = propertiesMapper;
     _protocolChartPresenter      = protocolChartPresenter;
     _protocolFactory             = protocolFactory;
     _protocolUpdater             = protocolUpdater;
     _protocolPropertiesDTOMapper = protocolPropertiesDTOMapper;
 }
        public void StartDispatching(TcpListener tcpListener, ILogger logger, IProtocolFactory protocolFactory, IAppDocument appDocument)
        {
            tcpListener.Start();

            //	Create the limited number of threads accepting connections.
            for (int indexThread = 0; indexThread < this.m_SizeThreadPool; indexThread++)
            {
                DispatchLoop dispatchLoop      = new DispatchLoop(tcpListener, logger, protocolFactory, appDocument);
                ThreadStart  clientThreadStart = new ThreadStart(dispatchLoop.RunDispatcher);
                Thread       clientThread      = new Thread(clientThreadStart);
                clientThread.Start();
                clientThread.IsBackground = true;
                logger.WriteEntry("Created and started Thread = " + clientThread.GetHashCode());
            }
        }
Exemple #15
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ExecuteOpOnScheduleProtocol"/> class.
        /// </summary>
        /// <param name="scheduleExecutionReadStream">The schedule execution read stream.</param>
        /// <param name="scheduleExecutionWriteStream">The schedule execution write stream.</param>
        /// <param name="protocolFactory">The factory to determine the appropriate protocol to execute the scheduled operation.</param>
        /// <param name="evaluateScheduleProtocol">The protocol to evaluate schedules.</param>
        public ExecuteOpOnScheduleProtocol(
            IReadOnlyStream scheduleExecutionReadStream,
            IWriteOnlyStream scheduleExecutionWriteStream,
            IProtocolFactory protocolFactory,
            ISyncAndAsyncReturningProtocol <EvaluateScheduleOp, bool> evaluateScheduleProtocol)
        {
            scheduleExecutionReadStream.MustForArg(nameof(scheduleExecutionReadStream)).NotBeNull();
            scheduleExecutionWriteStream.MustForArg(nameof(scheduleExecutionWriteStream)).NotBeNull();
            protocolFactory.MustForArg(nameof(protocolFactory)).NotBeNull();
            evaluateScheduleProtocol.MustForArg(nameof(evaluateScheduleProtocol)).NotBeNull();

            this.scheduleExecutionReadStream  = scheduleExecutionReadStream;
            this.scheduleExecutionWriteStream = scheduleExecutionWriteStream;
            this.protocolFactory          = protocolFactory;
            this.evaluateScheduleProtocol = evaluateScheduleProtocol;
        }
        public void Connect(IProtocolFactory factory, string addressString, int port)
        {
            IPAddress address;

            if (IPAddress.TryParse(addressString, out address))
            {
                Connect(factory, address, port);
            }
            else
            {
                IAsyncResult result = Dns.BeginGetHostEntry(addressString, null,
                    new Pair<string, int>(addressString, port));

                _reactor.AddResult(result, ResolveCompleted, 0, factory);
            }
        }
Exemple #17
0
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (processor != null)
         {
             processor.Dispose();
         }
         if (server != null)
         {
             ((IDisposable)server).Dispose();
         }
     }
     processor = null;
     factory   = null;
     server    = null;
     base.Dispose(disposing);
 }
Exemple #18
0
        protected override void Context()
        {
            _context         = A.Fake <IExecutionContext>();
            _protocolUpdater = A.Fake <IProtocolUpdater>();
            _protocolFactory = A.Fake <IProtocolFactory>();
            _project         = A.Fake <PKSimProject>();
            _oldProtocol     = A.Fake <Protocol>();
            _oldProtocolMode = ProtocolMode.Simple;
            _newProtocolMode = ProtocolMode.Advanced;

            A.CallTo(() => _context.CurrentProject).Returns(_project);
            A.CallTo(() => _context.Resolve <IProtocolUpdater>()).Returns(_protocolUpdater);
            A.CallTo(() => _context.Resolve <IProtocolFactory>()).Returns(_protocolFactory);

            _newProtocol = A.Fake <Protocol>();
            A.CallTo(() => _protocolFactory.Create(_newProtocolMode)).Returns(_newProtocol);
            sut = new SetProtocolModeCommand(_oldProtocol, _oldProtocolMode, _newProtocolMode, _context);
        }
Exemple #19
0
        protected override void Context()
        {
            _defaultIndividualRetriever = A.Fake <IDefaultIndividualRetriever>();
            _speciesRepository          = A.Fake <ISpeciesRepository>();
            _simulationFactory          = A.Fake <ISimulationFactory>();
            _parameterFactory           = A.Fake <IParameterFactory>();
            _protocolFactory            = A.Fake <IProtocolFactory>();

            sut       = new VSSCalculator(_defaultIndividualRetriever, _speciesRepository, _simulationFactory, _parameterFactory, _protocolFactory);
            _species1 = new Species().WithId("Human");
            _species2 = new Species().WithId("Dog");
            A.CallTo(() => _speciesRepository.All()).Returns(new[] { _species1, _species2 });

            _simulation = A.Fake <Simulation>();
            var organism = new Organism();

            organism.Add(DomainHelperForSpecs.ConstantParameterWithValue(0.5).WithName(CoreConstants.Parameter.HCT));
            A.CallTo(() => _simulation.Individual.Organism).Returns(organism);
        }
        protected override Task Context()
        {
            _parameterMapper     = A.Fake <ParameterMapper>();
            _schemaMapper        = A.Fake <SchemaMapper>();
            _protocolFactory     = A.Fake <IProtocolFactory>();
            _dimensionRepository = A.Fake <IDimensionRepository>();

            sut = new ProtocolMapper(_parameterMapper, _protocolFactory, _schemaMapper, _dimensionRepository);

            _simpleProtocol = new SimpleProtocol
            {
                ApplicationType = ApplicationTypes.Intravenous,
                DosingInterval  = DosingIntervals.DI_6_6_12,
                Name            = "Simple Protocol",
                Description     = "Simple Protocol description",
            };
            _simpleProtocol.Add(DomainHelperForSpecs.ConstantParameterWithValue(3).WithName(Constants.Parameters.START_TIME));
            _simpleProtocol.Add(DomainHelperForSpecs.ConstantParameterWithValue(4).WithName(CoreConstants.Parameters.INPUT_DOSE));
            _simpleProtocol.Add(DomainHelperForSpecs.ConstantParameterWithValue(5).WithName(Constants.Parameters.END_TIME));

            A.CallTo(() => _parameterMapper.MapToSnapshot(_simpleProtocol.StartTime)).Returns(new Parameter().WithName(_simpleProtocol.StartTime.Name));
            A.CallTo(() => _parameterMapper.MapToSnapshot(_simpleProtocol.Dose)).Returns(new Parameter().WithName(_simpleProtocol.Dose.Name));
            A.CallTo(() => _parameterMapper.MapToSnapshot(_simpleProtocol.EndTimeParameter)).Returns(new Parameter().WithName(_simpleProtocol.EndTimeParameter.Name));

            _advancedProtocol = new AdvancedProtocol
            {
                Name        = "Advanced Protocol",
                Description = "Advanced Protocol description",
                TimeUnit    = DomainHelperForSpecs.TimeDimensionForSpecs().DefaultUnit,
            };
            _schema = new Schema().WithName("Schema1");
            _advancedProtocol.AddSchema(_schema);
            _advancedProtocolParameter = DomainHelperForSpecs.ConstantParameterWithValue(3).WithName("AdvancedProtocolParameter");
            _advancedProtocol.Add(_advancedProtocolParameter);
            A.CallTo(() => _parameterMapper.MapToSnapshot(_advancedProtocolParameter)).Returns(new Parameter().WithName(_advancedProtocolParameter.Name));

            _snapshotSchema = new Snapshots.Schema().WithName(_schema.Name);
            A.CallTo(() => _schemaMapper.MapToSnapshot(_schema)).Returns(_snapshotSchema);

            A.CallTo(() => _dimensionRepository.Time).Returns(DomainHelperForSpecs.TimeDimensionForSpecs());

            return(Task.FromResult(true));
        }
        protected override void Context()
        {
            _view                      = A.Fake <ICreateProtocolView>();
            _propertiesMapper          = A.Fake <IBuildingBlockPropertiesMapper>();
            _simpleProtocolPresenter   = A.Fake <ISimpleProtocolPresenter>();
            _protocolFactory           = A.Fake <IProtocolFactory>();
            _propertiesDTOMapper       = A.Fake <IProtocolToProtocolPropertiesDTOMapper>();
            _advancedProtocolPresenter = A.Fake <IAdvancedProtocolPresenter>();
            _protocolUpdater           = A.Fake <IProtocolUpdater>();
            _protocolChartPresenter    = A.Fake <IProtocolChartPresenter>();
            _subPresenterManager       = A.Fake <ISubPresenterItemManager <IProtocolItemPresenter> >();
            _dialogCreator             = A.Fake <IDialogCreator>();
            A.CallTo(() => _protocolFactory.Create(ProtocolMode.Simple)).Returns(new SimpleProtocol());
            A.CallTo(() => _subPresenterManager.AllSubPresenters).Returns(new IProtocolItemPresenter[] { _simpleProtocolPresenter, _advancedProtocolPresenter });
            sut = new CreateProtocolPresenter(_view, _subPresenterManager, _propertiesMapper,
                                              _protocolChartPresenter, _protocolFactory, _protocolUpdater, _propertiesDTOMapper, _dialogCreator);

            sut.Initialize();
        }
    public void startDispatching(TcpListener listener, ILogger logger,
                               IProtocolFactory protoFactory)
    {
        // Run forever, accepting and spawning threads to service each connection

        for (;;) {
          try {
        listener.Start();
        Socket clntSock = listener.AcceptSocket();  // Block waiting for connection
        IProtocol protocol = protoFactory.createProtocol(clntSock, logger);
        Thread thread = new Thread(new ThreadStart(protocol.handleclient));
        thread.Start();
        logger.writeEntry("Created and started Thread = " + thread.GetHashCode());
          } catch (System.IO.IOException e) {
        logger.writeEntry("Exception = " + e.Message);
          }
        }
        /* NOT REACHED */
    }
        public void StartDispatching(TcpListener a_TcpListener, ILogger a_Logger, IDataSource a_DataSource, IProtocolFactory a_ProtocolFactory)
        {
            _tcpListener     = a_TcpListener;
            _logger          = a_Logger;
            _dataSource      = a_DataSource;
            _protocolFactory = a_ProtocolFactory;

            while (ContinueRunning())
            {
                try
                {
                    StartDispatcher();
                }
                catch (Exception e)
                {
                    _logger.WriteEntry("Exception: " + e.Message);
                }
            }
        }
Exemple #24
0
 public SocketHostedService(ISocketServer socketTcpServer,
                            ISocketClientDictionary <string, UserToken> socketClientDictionary,
                            IProtocolFactory protocolFactory,
                            ISocketSendServer socketSendServer,
                            IOptionsMonitor <CollectionSetting> kj1012CollectionSetting,
                            ILogger <SocketHostedService> logger)
 {
     _socketTcpServer                  = socketTcpServer;
     _socketClientDictionary           = socketClientDictionary;
     _protocolFactory                  = protocolFactory;
     _socketSendServer                 = socketSendServer;
     _kj1012CollectionSetting          = kj1012CollectionSetting.CurrentValue;
     _socketTcpServer.Listening       += SocketTcpServer_Listening;
     _socketTcpServer.ClientConnected += SocketTcpServer_ClientConnected;
     _socketTcpServer.ReceiveData     += SocketTcpServer_ReceiveData;
     _socketTcpServer.ClientClose     += SocketTcpServer_ClientClose;
     _socketTcpServer.Error           += SocketTcpServer_Error;
     _socketTcpServer.SetKeepAlive(true, 1000, 500);
     _logger = logger;
 }
 public void startDispatching(TcpListener listener, ILogger logger,
                              IProtocolFactory protoFactory)
 {
     // 무한히 실행하면서 연결 요청을 수락할 때마다 새로운 서비스 스레드를 생성한다.
     for (; ;)
     {
         try {
             listener.Start();
             Socket    clntSock = listener.AcceptSocket();   // 연결 요청을 대기하면서 블록을 건다.
             IProtocol protocol = protoFactory.createProtocol(clntSock, logger);
             Thread    thread   = new Thread(new ThreadStart(protocol.handleclient));
             thread.Start();
             logger.writeEntry("Created and started Thread = " + thread.GetHashCode());
         }
         catch (System.IO.IOException e) {
             logger.writeEntry("Exception = " + e.Message);
         }
     }
     // 이 곳으로는 도달하지 않는다.
 }
 public void BindToPeer(IProtocolFactory factory, IPEndPoint peer)
 {
     BindInternal(factory, new IPEndPoint(IPAddress.Any, 0), peer);
 }
Exemple #27
0
 void IContext.ConnectStream(IProtocolFactory factory, IPEndPoint local, IPEndPoint remote)
 {
     Connector.ConnectTcp(this.reactor, factory, local, remote);
 }
 public void Connect(IProtocolFactory factory, IPAddress address, int port)
 {
     Connect(factory, new IPEndPoint(address, port));
 }
Exemple #29
0
 /// <summary>
 /// Ctor.
 /// </summary>
 /// <param name="factory"></param>
 public ClassFactory(IProtocolFactory factory)
 {
     _currentFactory = factory;
 }
Exemple #30
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LoginListener"/> class.
 /// </summary>
 /// <param name="protocolFactory">The protocol factory reference to create a protocol that the listerner will follow.</param>
 /// <param name="dosDefender">A reference to the DoS defender service implementation.</param>
 /// <param name="port">The port where this listener will listen.</param>
 public LoginListener(IProtocolFactory protocolFactory, IDoSDefender dosDefender, int port = DefaultLoginListenerPort)
     : base(port, protocolFactory?.CreateForType(OpenTibiaProtocolType.LoginProtocol), dosDefender)
 {
 }
Exemple #31
0
 internal static void ConnectUdp(IReactor reactor, IProtocolFactory protocolFactory, IPEndPoint localEP, IPEndPoint remoteEP, int bufferSize = 524288)
 {
     IPeerConnector connector = new DatagramPeerConnector();
     connector.Bind(reactor, protocolFactory, localEP, remoteEP, bufferSize);
 }
Exemple #32
0
 public ProtocolMapper(ParameterMapper parameterMapper, IProtocolFactory protocolFactory, SchemaMapper schemaMapper, IDimensionRepository dimensionRepository) : base(parameterMapper)
 {
     _protocolFactory     = protocolFactory;
     _schemaMapper        = schemaMapper;
     _dimensionRepository = dimensionRepository;
 }
Exemple #33
0
        public static int Run <T>(string configuration, string[] args, IPEndPoint[] endpoints, IProtocolFactory protocolFactory)
            where T : IMessageProcessor, new()
        {
            try
            {
                AppDomain.CurrentDomain.UnhandledException += (s, e) => LogWhileDying(e.ExceptionObject);
                string name = null;
                bool   uninstall = false, install = false, benchmark = false, hasErrors = false;
                for (int i = 0; i < args.Length; i++)
                {
                    switch (args[i])
                    {
                    case "-u": uninstall = true; break;

                    case "-i": install = true; break;

                    case "-b": benchmark = true; break;

                    default:
                        if (args[i].StartsWith("-n:"))
                        {
                            name = args[i].Substring(3);
                        }
                        else
                        {
                            Console.Error.WriteLine("Unknown argument: " + args[i]);
                            hasErrors = true;
                        }
                        break;
                    }
                }
                if (hasErrors)
                {
                    Console.Error.WriteLine("Support flags:");
                    Console.Error.WriteLine("-i\tinstall service");
                    Console.Error.WriteLine("-u\tuninstall service");
                    Console.Error.WriteLine("-b\tbenchmark");
                    Console.Error.WriteLine("-n:name\toverride service name");
                    Console.Error.WriteLine("(no args) execute in console");
                    return(-1);
                }
                if (uninstall)
                {
                    Console.WriteLine("Uninstalling service...");
                    InstallerServiceName = name;
                    ManagedInstallerClass.InstallHelper(new string[] { "/u", typeof(T).Assembly.Location });
                }
                if (install)
                {
                    Console.WriteLine("Installing service...");
                    InstallerServiceName = name;
                    ManagedInstallerClass.InstallHelper(new string[] { typeof(T).Assembly.Location });
                }
                if (install || uninstall)
                {
                    Console.WriteLine("(done)");
                    return(0);
                }
                if (benchmark)
                {
                    var factory = BasicBinaryProtocolFactory.Default;
                    using (var svc = new TcpService("", new EchoProcessor(), factory))
                    {
                        svc.MaxIncomingQuota = -1;
                        Console.WriteLine("Running benchmark using " + svc.ServiceName + "....");
                        svc.StartService();
                        svc.RunEchoBenchmark(1, 500000, factory);
                        svc.RunEchoBenchmark(50, 10000, factory);
                        svc.RunEchoBenchmark(100, 5000, factory);
                        svc.StopService();
                    }
                    return(0);
                }

                if (Environment.UserInteractive)// user facing
                {
                    using (var messageProcessor = new T())
                        using (var svc = new TcpService(configuration, messageProcessor, protocolFactory))
                        {
                            svc.Endpoints = endpoints;
                            if (!string.IsNullOrEmpty(name))
                            {
                                svc.ActualServiceName = name;
                            }
                            svc.StartService();
                            Console.WriteLine("Running " + svc.ActualServiceName +
                                              " in interactive mode; press any key to quit");
                            Console.ReadKey();
                            Console.WriteLine("Exiting...");
                            svc.StopService();
                        }
                    return(0);
                }
                else
                {
                    var svc = new TcpService(configuration, new T(), protocolFactory);
                    svc.Endpoints = endpoints;
                    ServiceBase.Run(svc);
                    return(0);
                }
            }
            catch (Exception ex)
            {
                LogWhileDying(ex);
                return(-1);
            }
        }
Exemple #34
0
        public void AttachStream(IProtocolFactory factory, Stream readStream, Stream writeStream)
        {
            factory.StartedConnecting();

            Protocol protocol = factory.BuildProtocol();

            StreamConnection connection = new StreamConnection(this, protocol);

            connection.StartConnection(readStream, writeStream, protocol.ReceiveBufferSize);
            protocol.MakeConnection(connection);
        }
Exemple #35
0
 public void AttachStream(IProtocolFactory factory, Stream stream)
 {
     AttachStream(factory, stream, stream);
 }
Exemple #36
0
 public SocketListenerHost(SocketType transportProtocol, IPEndPoint endPoint, IProtocolFactory dataProtocolFactory)
 {
     _listener = new SocketListener(transportProtocol, endPoint, dataProtocolFactory);
 }
 public void Bind(IProtocolFactory factory, IPAddress localAddress, int localPort)
 {
     BindInternal(factory, new IPEndPoint(localAddress, localPort), null);
 }
Exemple #38
0
 public SocketListener(SocketType type, IPEndPoint host, IProtocolFactory factory)
     : this(type, host, factory.Create)
 {
     // _context = this.CreateContext(type, host);
 }
Exemple #39
0
 public void BindToPeerDatagram(IProtocolFactory factory, IPEndPoint peer)
 {
     DatagramSocketConnector connector = new DatagramSocketConnector(this);
     connector.BindToPeer(factory, peer);
 }
Exemple #40
0
 internal static void BindTcp(IReactor reactor, IProtocolFactory protocolFactory, IPEndPoint localEP, int bufferSize = 8192)
 {
     IConnector connector = new StreamConnector();
     connector.Bind(reactor, protocolFactory, localEP, bufferSize);
 }
Exemple #41
0
 public CacheClient(IProtocolFactory factory)
 {
     m_pooled   = factory.AquireProtocol();
     m_protocol = m_pooled.Item;
 }
Exemple #42
0
 public NotificationHandler(IProtocolFactory protocolFactory, ILocker locker, IWorld world)
 {
     this.protocolFactory = protocolFactory;
     this.locker          = locker;
     this.world           = world;
 }
Exemple #43
0
 void IContext.BindDatagram(IProtocolFactory factory, IPEndPoint local)
 {
     Connector.BindUdp(this.reactor, factory, local);
 }
Exemple #44
0
 public void ConnectStream(IProtocolFactory factory, IPAddress address, int port)
 {
     StreamSocketClientConnector connector = new StreamSocketClientConnector(this);
     connector.Connect(factory, address, port);
 }
 public void BindToPeer(IProtocolFactory factory, IPAddress address, int port)
 {
     BindInternal(factory, new IPEndPoint(IPAddress.Any, 0), new IPEndPoint(address, port));
 }
 public ProtocolsLayer(IProtocolFactory protocolFactory)
 {
     this._protocolFactory = protocolFactory;
 }
Exemple #47
0
 public void ConnectStream(IProtocolFactory factory, IPEndPoint peer)
 {
     StreamSocketClientConnector connector = new StreamSocketClientConnector(this);
     connector.Connect(factory, peer);
 }
        protected override void Context()
        {
            _vssCalculator               = A.Fake <IVSSCalculator>();
            _parameterFactory            = A.Fake <IParameterFactory>();
            _protocolMapper              = A.Fake <IProtocolToSchemaItemsMapper>();
            _protocolFactory             = A.Fake <IProtocolFactory>();
            _globalPKAnalysisRunner      = A.Fake <IGlobalPKAnalysisRunner>();
            _pkCalculationOptionsFactory = A.Fake <IPKCalculationOptionsFactory>();
            _pkAnalysisTask              = A.Fake <IPKAnalysesTask>();
            _interactionTask             = A.Fake <IInteractionTask>();
            _cloner = A.Fake <ICloner>();
            sut     = new GlobalPKAnalysisTask(_parameterFactory, _protocolMapper, _protocolFactory, _globalPKAnalysisRunner,
                                               _pkAnalysisTask, _pkCalculationOptionsFactory, _vssCalculator, _interactionTask, _cloner);

            var baseGrid = new BaseGrid("time", A.Fake <IDimension>());

            _peripheralVenousBloodPlasma = CalculationColumnFor(baseGrid, CoreConstants.Organ.PeripheralVenousBlood, CoreConstants.Observer.PLASMA_PERIPHERAL_VENOUS_BLOOD, CoreConstants.Observer.PLASMA_PERIPHERAL_VENOUS_BLOOD, _compoundName);
            _venousBloodPlasma           = CalculationColumnFor(baseGrid, CoreConstants.Organ.VenousBlood, CoreConstants.Compartment.Plasma, CoreConstants.Observer.CONCENTRATION_IN_CONTAINER, _compoundName);

            _individual = A.Fake <Individual>();
            _species    = new Species();
            A.CallTo(() => _individual.Species).Returns(_species);

            _compound           = new Compound().WithName(_compoundName);
            _compoundProperties = new CompoundProperties {
                Compound = _compound
            };
            _simulationSchemaItems = new List <SchemaItem>();
            _protocol = new SimpleProtocol();
            _compoundProperties.ProtocolProperties.Protocol = _protocol;
            A.CallTo(() => _protocolMapper.MapFrom(_protocol)).Returns(_simulationSchemaItems);

            _simulation = new IndividualSimulation {
                Properties = new SimulationProperties()
            };

            _simulation.Properties.AddCompoundProperties(_compoundProperties);
            _simulation.AddUsedBuildingBlock(new UsedBuildingBlock("CompId", PKSimBuildingBlockType.Compound)
            {
                BuildingBlock = _compound
            });
            _simulation.AddUsedBuildingBlock(new UsedBuildingBlock("IndividualId", PKSimBuildingBlockType.Individual)
            {
                BuildingBlock = _individual
            });
            _simulation.DataRepository = new DataRepository {
                _venousBloodPlasma, _peripheralVenousBloodPlasma
            };

            _venousBloodPK = new PKValues();
            _venousBloodPK.AddValue(Constants.PKParameters.Vss, 10);
            _venousBloodPK.AddValue(Constants.PKParameters.Vd, 11);
            _venousBloodPK.AddValue(Constants.PKParameters.CL, 12);

            _venousBloodPK.AddValue(Constants.PKParameters.AUC_inf, 13);
            _venousBloodPK.AddValue(Constants.PKParameters.AUC_inf_tD1_norm, 14);

            _peripheralVenousBloodPK = new PKValues();
            _peripheralVenousBloodPK.AddValue(Constants.PKParameters.Vss, 21);
            _peripheralVenousBloodPK.AddValue(Constants.PKParameters.Vd, 22);
            _peripheralVenousBloodPK.AddValue(Constants.PKParameters.CL, 23);
            _peripheralVenousBloodPK.AddValue(Constants.PKParameters.AUC_inf, 24);
            _peripheralVenousBloodPK.AddValue(Constants.PKParameters.AUC_inf_tD1_norm, 25);
            _peripheralVenousBloodPK.AddValue(Constants.PKParameters.C_max, 26);
            _peripheralVenousBloodPK.AddValue(Constants.PKParameters.C_max_tDLast_tDEnd, 27);


            A.CallTo(() => _pkAnalysisTask.CalculatePK(_venousBloodPlasma, A <PKCalculationOptions> ._)).Returns(_venousBloodPK);
            A.CallTo(() => _pkAnalysisTask.CalculatePK(_peripheralVenousBloodPlasma, A <PKCalculationOptions> ._)).Returns(_peripheralVenousBloodPK);
            A.CallTo(() => _parameterFactory.CreateFor(A <string> ._, A <double> ._, A <string> ._, PKSimBuildingBlockType.Simulation))
            .ReturnsLazily(s => new PKSimParameter().WithName((string)s.Arguments[0])
                           .WithDimension(A.Fake <IDimension>())
                           .WithFormula(new ConstantFormula((double)s.Arguments[1])));
        }
Exemple #49
0
        public ConnectorHandle ListenStream(IProtocolFactory factory, int port, IPAddress address)
        {
            StreamSocketServerConnector connector = new StreamSocketServerConnector(this);
            connector.Listen(factory, port, address);

            return new ConnectorHandle(connector);
        }
Exemple #50
0
 void IContext.BindStream(IProtocolFactory factory, IPEndPoint local)
 {
     Connector.BindTcp(this.reactor, factory, local);
 }
Exemple #51
0
        public ConnectorHandle ListenStream(IProtocolFactory factory)
        {
            StreamSocketServerConnector connector = new StreamSocketServerConnector(this);
            connector.Listen(factory);

            return new ConnectorHandle(connector);
        }
Exemple #52
0
 public VSSCalculator(IDefaultIndividualRetriever defaultIndividualRetriever, ISpeciesRepository speciesRepository,
                      ISimulationFactory simulationFactory, IParameterFactory parameterFactory, IProtocolFactory protocolFactory)
 {
     _defaultIndividualRetriever = defaultIndividualRetriever;
     _speciesRepository          = speciesRepository;
     _simulationFactory          = simulationFactory;
     _parameterFactory           = parameterFactory;
     _protocolFactory            = protocolFactory;
 }
Exemple #53
0
 public static int Run<T>(string configuration, string[] args, IPEndPoint[] endpoints, IProtocolFactory protocolFactory)
     where T : IMessageProcessor, new()
     => Run<T>(configuration, args, endpoints, protocolFactory, Console.Out, Console.Error);
Exemple #54
0
 public void BindDatagram(IProtocolFactory factory)
 {
     DatagramSocketConnector connector = new DatagramSocketConnector(this);
     connector.Bind(factory);
 }
Exemple #55
0
 public ApplicationProtocolMapper(IProtocolFactory protocolFactory, IBatchLogger logger)
 {
     _protocolFactory = protocolFactory;
     _logger          = logger;
 }
Exemple #56
0
        void RunEchoClient(int iterations, ref int outstanding, ManualResetEvent evt, Stopwatch mainWatch, IProtocolFactory factory)
        {
            Task <object> last    = null;
            var           message = Encoding.UTF8.GetBytes("hello");

            using (var client = new TcpClient())
            {
                client.ProtocolFactory = factory;
                client.Open(new IPEndPoint(IPAddress.Loopback, 5999));

                if (Interlocked.Decrement(ref outstanding) == 0)
                {
                    mainWatch.Start();
                    evt.Set();
                }
                else
                {
                    evt.WaitOne();
                }

                var watch = Stopwatch.StartNew();
                for (int i = 0; i < iterations; i++)
                {
                    last = client.Execute(message);
                }
                last.Wait();
                watch.Stop();
                //Console.WriteLine("{0}ms", watch.ElapsedMilliseconds);
            }
        }
Exemple #57
0
 public void BindDatagram(IProtocolFactory factory, IPAddress localAddress, int localPort)
 {
     DatagramSocketConnector connector = new DatagramSocketConnector(this);
     connector.Bind(factory, localAddress, localPort);
 }
 public DispatchLoop(TcpListener listener, ILogger logger, IProtocolFactory protoFactory)
 {
     this.listener     = listener;
     this.logger       = logger;
     this.protoFactory = protoFactory;
 }
Exemple #59
0
 public void BindToPeerDatagram(IProtocolFactory factory, IPAddress address, int port)
 {
     DatagramSocketConnector connector = new DatagramSocketConnector(this);
     connector.BindToPeer(factory, address, port);
 }