Esempio n. 1
0
        public bool Start(HostControl hostControl)
        {
            #region Настройка из кода
            //_ordersHost = ServiceHostHelper.ConfigureServiceHost(_ordersHost, ContractDescription.GetContract(typeof(IOrderService)), String.Empty);
            //_productsHost = ServiceHostHelper.ConfigureServiceHost(_productsHost, ContractDescription.GetContract(typeof(IProductService)), String.Empty);
            //_categoriesHost = ServiceHostHelper.ConfigureServiceHost(_categoriesHost, ContractDescription.GetContract(typeof(ICategoryService)), String.Empty, true);
            #endregion
            var ordersResetEvent = new ManualResetEvent(false);
            var catResetEvent    = new ManualResetEvent(false);
            var prodResetEvent   = new ManualResetEvent(false);

            _ordersHost.BeginOpen(ar =>
            {
                _ordersHost.EndOpen(ar);
                ordersResetEvent.Set();
            }, null);
            _productsHost.BeginOpen(ar =>
            {
                _productsHost.EndOpen(ar);
                prodResetEvent.Set();
            }, null);
            _categoriesHost.BeginOpen(ar =>
            {
                _categoriesHost.EndOpen(ar);
                catResetEvent.Set();
            }, null);

            WaitHandle.WaitAll(new WaitHandle[] { ordersResetEvent, catResetEvent, prodResetEvent });

            return(true);
        }
Esempio n. 2
0
        private static void Main(string[] args)
        {
            var serviceHost = new ServiceHost(typeof(EchoService));

            serviceHost.BeginOpen(serviceHost.EndOpen, null);

            Console.WriteLine("Service running.");
            Console.WriteLine("Press <ENTER> to stop.");
            Console.ReadLine();
        }
 public void Open()
 {
     if (host != null)
     {
         Dispose();
     }
     IsDisposed = false;
     service    = new MyService();
     host       = new ServiceHost(service, new Uri(Constants.myPipeService));
     host.AddServiceEndpoint(typeof(IMyService), new NetNamedPipeBinding(), Constants.myPipeServiceName);
     host.BeginOpen(OnOpen, host);
 }
Esempio n. 4
0
        public static IDisposable Start <T>(T instance, string name) where T : class
        {
            var host = new ServiceHost(instance, new[] { new Uri("net.pipe://localhost") });

            host.AddServiceEndpoint(typeof(T), new NetNamedPipeBinding(), name);

            var behaviour = host.Description.Behaviors.Find <ServiceBehaviorAttribute>();

            behaviour.InstanceContextMode = InstanceContextMode.Single;
            host.BeginOpen(o => Program.Logger.Debug("Host opened: " + host.BaseAddresses[0].AbsoluteUri), null);
            return(host);
        }
Esempio n. 5
0
        public static IDisposable Start <T>(T instance, int port) where T : class
        {
            var tcpBaseAddress = new Uri(string.Format("net.tcp://localhost:{0}/", port));
            var tcpBinding     = GetDefaultNetTcpBinding();

            var host = new ServiceHost(instance, new[] { tcpBaseAddress });

            host.AddServiceEndpoint(typeof(T), tcpBinding, instance.GetType().Name);

            var behaviour = host.Description.Behaviors.Find <ServiceBehaviorAttribute>();

            behaviour.InstanceContextMode = InstanceContextMode.Single;

            host.BeginOpen(o => Program.Logger.Debug("Host opened: " + tcpBaseAddress), null);
            return(host);
        }
Esempio n. 6
0
        public Main(String [] args) : this()
        {
            try
            {
                using (ChannelFactory <DNRIService> serviceFactory = new ChannelFactory <DNRIService>(new NetNamedPipeBinding(), new EndpointAddress(PipeService)))
                {
                    var channel = serviceFactory.CreateChannel();
                    if (channel.IsOnline())
                    {
                        foreach (var argument in args)
                        {
                            var argTrim = argument.Trim();
                            if (argTrim.EndsWith(".dnt"))
                            {
                                channel.OpenDnt(argument);
                            }
                            else if (argTrim.EndsWith(".pak"))
                            {
                                channel.OpenPak(argument);
                            }
                        }
                        channel.Activate();
                        Close();
                    }
                }
            }
            catch
            {
                @this = new ServiceHost(this, new Uri(PipeName));
                @this.AddServiceEndpoint(typeof(DNRIService), new NetNamedPipeBinding(), PipeService);
                @this.BeginOpen((IAsyncResult ar) => @this.EndOpen(ar), null);

                foreach (var argument in args)
                {
                    var argTrim = argument.Trim();
                    if (argTrim.EndsWith(".dnt"))
                    {
                        OpenDnt(argument);
                    }
                    else if (argTrim.EndsWith(".pak"))
                    {
                        OpenPak(argument);
                    }
                }
            }
        }
Esempio n. 7
0
        public bool Start(HostControl hostControl)
        {
            #region Настройка из кода
            //_ordersHost = ServiceHostHelper.ConfigureServiceHost(_ordersHost, ContractDescription.GetContract(typeof(IOrderService)), String.Empty);
            //_productsHost = ServiceHostHelper.ConfigureServiceHost(_productsHost, ContractDescription.GetContract(typeof(IProductService)), String.Empty);
            //_categoriesHost = ServiceHostHelper.ConfigureServiceHost(_categoriesHost, ContractDescription.GetContract(typeof(ICategoryService)), String.Empty, true);
            #endregion
            _ordersHost.BeginOpen(OnOpen, _ordersHost);
            _productsHost.BeginOpen(OnOpen, _productsHost);
            _categoriesHost.BeginOpen(OnOpen, _categoriesHost);

            /*while (_ordersHost.State != CommunicationState.Opened && _categoriesHost.State != CommunicationState.Opened && _productsHost.State != CommunicationState.Opened)
             * {
             *      Thread.Sleep(100);
             * }*/

            return(true);
        }
Esempio n. 8
0
        } // ToTray


        /// <inheritdoc />
        /// <summary>
        /// Асинхронно запускает сервер.
        /// </summary>
        public bool StartServerAsync()
        {
            try {
                // Создание экземпляра класса-хоста, который публикует службу 
                // (указывается сервис-контракт и адрес службы).
                Host = new ServiceHost(typeof(CheckersSvc), new Uri($@"net.tcp://{View.TextBoxHostName.Text}:{View.TextBoxPort.Text}/Checkers"));

                // Для связи используем протокол TCP-IP.
                var netTcpBinding = new NetTcpBinding {
                    CloseTimeout = new TimeSpan(0, 0, 2, 0),
                    OpenTimeout = new TimeSpan(0, 0, 2, 0),
                    ReceiveTimeout = new TimeSpan(0, 0, 10, 0),
                    SendTimeout = new TimeSpan(0, 0, 2, 0),
                    TransactionFlow = false,
                    TransferMode = TransferMode.Buffered,
                    TransactionProtocol = TransactionProtocol.OleTransactions,
                    HostNameComparisonMode = HostNameComparisonMode.StrongWildcard,
                    // Максимум игроков в очереди на подключение
                    ListenBacklog = 10,
                    MaxBufferPoolSize = 1000000,
                    MaxBufferSize = 2055360000,
                    MaxReceivedMessageSize = 2055360000,
                    // Максимум игроков 20
                    MaxConnections = 20
                };

                // Задание конечных точек для сервиса.
                Host.AddServiceEndpoint(typeof(ICheckersSvc), netTcpBinding, "Game");

                View.Dispatcher.Invoke(() => {
                    View.StatusText.Text = "Запуск...";
                }, DispatcherPriority.Normal);

                // Старт службы (асинхронно).
                Host.BeginOpen(OpenCallbackAsync, null);
                ToTray("Сервер сейчас запущен.");
                return true;
            } catch (Exception e) {
                Console.WriteLine(e.Message);
                return false;
            } // try-catch
        } // StartServerAsync
Esempio n. 9
0
        public void Start(Action Successfully = null, Action Failed = null)
        {
            //резервация url (вопрос с правами администратора)
            //System.Diagnostics.Process.Start("CMD.exe", string.Format("netsh http add urlacl url=http://+:{0}/{1} user={2}", _port, _serviceName, Environment.UserName));

            _host = new ServiceHost(_serviceType, new Uri(_connectionString));
            _host.AddServiceEndpoint(_implementedContract, new WebHttpBinding(), new Uri(_connectionString)).Behaviors.Add(new CommHttpBehavior());

            _host.BeginOpen((res) =>
            {
                if (res.IsCompleted && _host.State == CommunicationState.Opened)
                {
                    Successfully?.Invoke();
                }
                else
                {
                    Failed?.Invoke();
                }
            }, null);
        }
Esempio n. 10
0
        } // MainWindow


        /// <summary>Старт службы</summary>
        private async void ButtonStart_OnClickAsync(object sender, RoutedEventArgs e)
        {
            // Создание экземпляра класса-хоста, который публикует службу 
            // (указывается сервис-контракт и адрес сервиса (службы))
            Host = new ServiceHost(typeof(Service), new Uri($@"net.tcp://{TextBoxHostName.Text}:{TextBoxPort.Text}/TicTacToe"));

            // Для связи используем протокол TCP-IP
            var netTcpBinding = new NetTcpBinding {
                CloseTimeout = new TimeSpan(0, 0, 2, 0),
                OpenTimeout = new TimeSpan(0, 0, 2, 0),
                ReceiveTimeout = new TimeSpan(0, 0, 10, 0),
                SendTimeout = new TimeSpan(0, 0, 2, 0),
                TransactionFlow = false,
                TransferMode = TransferMode.Buffered,
                TransactionProtocol = TransactionProtocol.OleTransactions,
                HostNameComparisonMode = HostNameComparisonMode.StrongWildcard,
                // Максимум игроков в очереди на подключение
                ListenBacklog = 10,
                MaxBufferPoolSize = 1000000,
                MaxBufferSize = 2055360000,
                MaxReceivedMessageSize = 2055360000,
                // Максимум игроков 20
                MaxConnections = 20
            };
            
            // Задание конечных точек для сервиса
            Host.AddServiceEndpoint(typeof(IService), netTcpBinding, "Game");

            // Асинхронный вызов уведомления в статус-баре в текущем потоке диспетчера
            await Dispatcher.InvokeAsync(() => {
                Status.Text = "Запуск...";
                ButtonStart.IsEnabled = false;
            }, DispatcherPriority.Normal);

            // Старт сервиса (асинхронно)
            Host.BeginOpen(OpenCallbackAsync, null);
        } // ButtonStart_OnClickAsync
Esempio n. 11
0
        /// <summary>
        /// 싱글턴 어트리뷰트를 사용하는 서비스를 wcf서버에 등록하기
        /// </summary>
        /// <param name="server_url"></param>
        /// <param name="NameSpace"></param>
        override protected void CreateService(Uri server_url, string NameSpace, MessageCredentialType MessageCredentialType)
        {
            //서버가 null일 경우는 그 즉시 생성하여 작업
            if (server == null)
            {
                server = new ServiceHost(service);
            }

            //URL중복 방지
            foreach (Uri url in server.BaseAddresses)
            {
                if (url == server_url)
                {
                    return;
                }
            }

            //HTTPS프로토콜 사용한 URL인지 판단
            bool useHTTPS = false;

            if (((server_url.AbsoluteUri).Replace(" ", string.Empty).Substring(0, 5).ToLower()).Contains("https"))
            {
                useHTTPS = true;
            }
            //웹서비스 오픈 준비
            try
            {
                //바인딩 설정
                Binding bind = SetBinding(base.bindType, MessageCredentialType);
                //메타데이터 작성
                setMetaData(server, NameSpace, server_url, useHTTPS);
                //Address(A:server_url)Binding(B:bind)Contract(C:service) 설정()
                bind.Namespace = NameSpace;
                server.AddServiceEndpoint(this.service.GetType(), bind, server_url);
                //SetCertificate(CertificationPath);
                server.BeginOpen(new AsyncCallback(ServiceBeginOpen_Callback), server);
            }
            catch (Exception ex)
            {
                server.Close();
                server = null;
                throw ex;
            }
        }
Esempio n. 12
0
        public static unsafe int OnLoad(IntPtr vmPtr, IntPtr optionsPtr, IntPtr reserved)
        {
            _loaded = true;

            JavaVM vm = JavaVM.GetOrCreateInstance(new JavaVMHandle(vmPtr));

            string optionsString = null;

            if (optionsPtr != IntPtr.Zero)
            {
                optionsString = ModifiedUTF8Encoding.GetString((byte *)optionsPtr);
            }

            string[] options = new string[0];
            if (optionsString != null)
            {
                options = optionsString.Split(',', ';');
            }

#if false
            // quick test
            GetEnvironmentVersion(vm);

            Action <JavaVM> action = GetEnvironmentVersion;
            IAsyncResult    result = action.BeginInvoke(vm, null, null);
            result.AsyncWaitHandle.WaitOne();
#endif

            AppDomain.CurrentDomain.AssemblyResolve += HandleAssemblyResolve;

            if (options.Contains("ShowAgentExceptions", StringComparer.OrdinalIgnoreCase))
            {
                AppDomain.CurrentDomain.FirstChanceException += HandleFirstChanceException;
                AppDomain.CurrentDomain.UnhandledException   += HandleUnhandledException;
                //AppDomain.CurrentDomain.ProcessExit += HandleProcessExit;
            }

            if (options.Contains("DisableStatementStepping", StringComparer.OrdinalIgnoreCase))
            {
                JavaVM.DisableStatementStepping = true;
            }

            List <WaitHandle> waitHandles = new List <WaitHandle>();
            Binding           binding;

            /*
             * start the wcf services and wait for the client to connect
             */

#if false
            /* IJvmEventsService
             */
            _jvmEventsPublisherHost = new ServiceHost(typeof(JvmEventsPublisher));
            Binding binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None)
            {
                ReceiveTimeout = TimeSpan.MaxValue,
                SendTimeout    = TimeSpan.MaxValue
            };

            _jvmEventsPublisherHost.AddServiceEndpoint(typeof(IJvmEventsService), binding, "net.pipe://localhost/Tvl.Java.DebugHost/JvmEventsService/");
            IAsyncResult jvmEventsPublisherStartResult = _jvmEventsPublisherHost.BeginOpen(null, null);
            waitHandles.Add(jvmEventsPublisherStartResult.AsyncWaitHandle);

            /* IJvmToolsInterfaceService
             */
            _jvmToolsInterfaceHost = new ServiceHost(typeof(JvmToolsInterfaceService));
            binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None)
            {
                ReceiveTimeout = TimeSpan.MaxValue,
                SendTimeout    = TimeSpan.MaxValue
            };

            _jvmToolsInterfaceHost.AddServiceEndpoint(typeof(IJvmToolsInterfaceService), binding, "net.pipe://localhost/Tvl.Java.DebugHost/JvmToolsInterfaceService/");
            IAsyncResult toolsInterfaceStartResult = _jvmToolsInterfaceHost.BeginOpen(null, null);
            waitHandles.Add(toolsInterfaceStartResult.AsyncWaitHandle);

            /* IJvmDebugSessionService
             */
            _jvmDebugSessionHost = new ServiceHost(typeof(JvmDebugSessionService));
            binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None)
            {
                ReceiveTimeout = TimeSpan.MaxValue,
                SendTimeout    = TimeSpan.MaxValue
            };

            _jvmDebugSessionHost.AddServiceEndpoint(typeof(IJvmDebugSessionService), binding, "net.pipe://localhost/Tvl.Java.DebugHost/JvmDebugSessionService/");
            IAsyncResult debugSessionStartResult = _jvmDebugSessionHost.BeginOpen(null, null);
            waitHandles.Add(debugSessionStartResult.AsyncWaitHandle);
#endif

            /* IDebugProtocolService
             */
            var debugProtocolService = new DebugProtocolService(vm);
            _debugProtocolHost = new ServiceHost(debugProtocolService);
            binding            = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None)
            {
                MaxReceivedMessageSize = 10 * 1024 * 1024,
                ReceiveTimeout         = TimeSpan.MaxValue,
                SendTimeout            = TimeSpan.MaxValue
            };

            _debugProtocolHost.AddServiceEndpoint(typeof(IDebugProtocolService), binding, "net.pipe://localhost/Tvl.Java.DebugHost/DebugProtocolService/");
            IAsyncResult debugProtocolStartResult = _debugProtocolHost.BeginOpen(null, null);
            waitHandles.Add(debugProtocolStartResult.AsyncWaitHandle);

            /* Wait for the services to finish opening
             */
            WaitHandle.WaitAll(waitHandles.ToArray());

            EventWaitHandle eventWaitHandle = null;
            try
            {
                eventWaitHandle = EventWaitHandle.OpenExisting(string.Format("JavaDebuggerInitHandle{0}", Process.GetCurrentProcess().Id));
            }
            catch (WaitHandleCannotBeOpenedException)
            {
                // must have been launched without the debugger
            }

            if (eventWaitHandle != null)
            {
                eventWaitHandle.Set();
                Action           waitAction  = _debuggerAttachComplete.Wait;
                IAsyncResult     waitResult  = waitAction.BeginInvoke(vm.HandleAsyncOperationComplete, null);
                DispatcherFrame  frame       = new DispatcherFrame(true);
                JvmtiEnvironment environment = debugProtocolService.Environment;
                vm.PushDispatcherFrame(frame, environment, waitResult);
            }

            return(0);
        }
Esempio n. 13
0
 /// <summary>
 /// Begins an asynchronous operation to open a communication object within a specified interval of time.
 /// </summary>
 /// <param name="timeout">The System.Timespan that specifies how long the send operation has to complete before timing out.</param>
 /// <param name="callback">The System.AsyncCallback delegate that receives notification of the completion of the asynchronous open operation.</param>
 /// <param name="state">An object, specified by the application, that contains state information associated with the asynchronous open operation.</param>
 /// <returns>The System.IAsyncResult that references the asynchronous open operation.</returns>
 public IAsyncResult BeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
 {
     return(ServiceHost.BeginOpen(timeout, callback, state));
 }