Disconnect() 공개 메소드

public Disconnect ( ) : void
리턴 void
예제 #1
1
        private async void StartInternal(CancellationToken cancellationToken)
        {
            byte[] buffer = new byte[256];
            var commandBuilder = new StringBuilder();

            var serverStream = new NamedPipeServerStream(this.PipeName, PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 0, 0);

            using (cancellationToken.Register(() => serverStream.Close()))
            {
                while (!cancellationToken.IsCancellationRequested)
                {
                    await Task.Factory.FromAsync(serverStream.BeginWaitForConnection, serverStream.EndWaitForConnection, TaskCreationOptions.None);

                    int read = await serverStream.ReadAsync(buffer, 0, buffer.Length);
                    commandBuilder.Append(Encoding.ASCII.GetString(buffer, 0, read));

                    while (!serverStream.IsMessageComplete)
                    {
                        read = serverStream.Read(buffer, 0, buffer.Length);
                        commandBuilder.Append(Encoding.ASCII.GetString(buffer, 0, read));
                    }

                    var response = this.HandleReceivedCommand(commandBuilder.ToString());
                    var responseBytes = Encoding.ASCII.GetBytes(response);
                    serverStream.Write(responseBytes, 0, responseBytes.Length);

                    serverStream.WaitForPipeDrain();
                    serverStream.Disconnect();

                    commandBuilder.Clear();
                }
            }
        }
예제 #2
0
    private void server()
    {
        System.IO.Pipes.NamedPipeServerStream pipeServer = new System.IO.Pipes.NamedPipeServerStream("testpipe", System.IO.Pipes.PipeDirection.InOut, 4);

        StreamReader sr = new StreamReader(pipeServer);
        StreamWriter sw = new StreamWriter(pipeServer);

        do
        {
            try
            {
                pipeServer.WaitForConnection();
                string test;
                sw.WriteLine("Waiting");
                sw.Flush();
                pipeServer.WaitForPipeDrain();
                test = sr.ReadLine();
                Console.WriteLine(test);
            }

            catch (Exception ex)
            { throw ex; }

            finally
            {
                pipeServer.WaitForPipeDrain();
                if (pipeServer.IsConnected)
                {
                    pipeServer.Disconnect();
                }
            }
        } while (true);
    }
예제 #3
0
        private static void Listen()
        {
            NamedPipeServerStream pipeServer =
                new NamedPipeServerStream(MyPipeName,
                                          PipeDirection.In,
                                          1,
                                          PipeTransmissionMode.Message,
                                          PipeOptions.None);

            StreamReader sr = new StreamReader(pipeServer);

            do
            {
                pipeServer.WaitForConnection();
                string fileName = sr.ReadLine();

                Console.WriteLine(fileName);

                Process proc = new Process();
                proc.StartInfo.FileName = fileName;
                proc.StartInfo.UseShellExecute = true;
                proc.Start();

                pipeServer.Disconnect();
            } while (true);
        }
예제 #4
0
    private static void ServerThread(object data)
    {
        //Creamos el pipe
        NamedPipeServerStream pipeServer =
            new NamedPipeServerStream("testpipe", PipeDirection.InOut, numThreads);

        Console.WriteLine(StringResources.ServidorIniciado);
        while (true)
        {
            Console.WriteLine(StringResources.EsperandoConexion);
            //Esperamos conexiones
            pipeServer.WaitForConnection();
            Console.WriteLine(StringResources.ClienteConectado);

            try
            {
                //Creamos un StreamString usando el pipe
                StreamString ss = new StreamString(pipeServer);

                //Recibimos el comando del cliente a través del Pipe
                string command = ss.ReadString();
                Console.WriteLine(StringResources.ComandoRecibido+":"+command);
                //Ejecutamos el proceso,redirigiendo la salida al pipe
                ProcessStartInfo pinfo = new ProcessStartInfo();
                pinfo.UseShellExecute = false;
                pinfo.RedirectStandardOutput = true;
                pinfo.FileName= ConfigurationManager.AppSettings.Get("powershellPath");
                pinfo.Arguments = '"'+command+ '"';
                using(Process process = Process.Start(pinfo))
                {
                    using (StreamReader reader = process.StandardOutput)
                    {
                        String line = reader.ReadLine();
                        while ( line != null )
                        {
                            ss.WriteString(line);
                            line = reader.ReadLine();
                        }

                        ss.WriteString("##END##");
                        Console.WriteLine(StringResources.ComandoTerminado);
                    }
                }
                           }
            // Catch the IOException that is raised if the pipe is broken
            // or disconnected.
            catch (IOException e)
            {
                Console.WriteLine("ERROR: {0}", e.Message);
            }
            pipeServer.Disconnect();
        }
    }
예제 #5
0
        internal void Run()
        {
            // Create pipe instance
            using (var pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.InOut, 4))
            {
                Console.WriteLine("[SJPS] Thread created");
                // wait for connection
                Console.WriteLine("[SJPS] Waiting for connection");
                pipeServer.WaitForConnection();
                Console.WriteLine("[SJPS] Client has connected");
                IsRunning = true;
                pipeServer.ReadTimeout = 1000;

                // Stream for the request.
                var sr = new StreamReader(pipeServer);
                // Stream for the response.
                var sw = new StreamWriter(pipeServer) {AutoFlush = true};

                while (IsRunning)
                {
                    try
                    {
                        // Read request from the stream.
                        var echo = sr.ReadLine();
                        Console.WriteLine("[SJPS] Recieved request: " + echo);

                        if (echo == "Close")
                        {
                            IsRunning = false;
                            break;
                        }

                        try
                        {
                            ParseRequest(echo);
                            sw.WriteLine("Ack");
                        }
                        catch (Exception)
                        {
                            sw.WriteLine("Error");
                        }
                    }
                    catch (IOException e)
                    {
                        Console.WriteLine("[SJPS] Error: {0}", e.Message);
                        IsRunning = false;
                    }
                }

                pipeServer.Disconnect();
                pipeServer.Close();
            }
        }
예제 #6
0
        private static void ExecuteThread()
        {
            Debug.WriteLine("\n*** Named pipe server stream starting (" + Program.PROCESS_PIPE_NAME + ") ***\n");

            var pipeServer = new NamedPipeServerStream(Program.PROCESS_PIPE_NAME, PipeDirection.InOut, 1);
            int threadId = Thread.CurrentThread.ManagedThreadId;

            while (run)
            {
                pipeServer.WaitForConnection();

                try
                {
                    StreamString ss = new StreamString(pipeServer);
                    var incoming = ss.ReadString();

                    Debug.WriteLine("Incoming command from pipe: " + incoming);
                    ss.WriteString("OK");
                    pipeServer.Disconnect();

                    if (incoming.Length <= 0)
                    {
                        continue;
                    }

                    string[] commandParts = incoming.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    CommandProcessor.Process(commandParts);
                }
                catch (IOException e)
                {
                    Debug.WriteLine("\n*** ERROR - Named pipe server stream failed, exception details follow [will try to continue] (" + Program.PROCESS_PIPE_NAME + ") ***\n\n {0} \n\n", e.Message);

                    try
                    {
                        pipeServer.Disconnect();
                    }
                    catch (Exception) { }
                }
            }
        }
        /// <summary>
        /// Connect from core to the service - used in core to listen for commands from the service
        /// </summary>
        public static void ConnectToService()
        {
            if (connected) return; //only one connection...

            Async.Queue("MBService Connection", () =>
            {
                using (NamedPipeServerStream pipe = new NamedPipeServerStream(MBSERVICE_OUT_PIPE,PipeDirection.In))
                {
                    connected = true;
                    bool process = true;
                    while (process)
                    {
                        pipe.WaitForConnection(); //wait for the service to tell us something
                        try
                        {
                            // Read the request from the service.
                            StreamReader sr = new StreamReader(pipe);

                            string command = sr.ReadLine();
                            switch (command.ToLower())
                            {
                                case IPCCommands.ReloadItems:
                                    //refresh just finished, we need to re-load everything
                                    Logger.ReportInfo("Re-loading due to request from service.");
                                    Application.CurrentInstance.ReLoad();
                                    break;
                                case IPCCommands.Shutdown:
                                    //close MB
                                    Logger.ReportInfo("Shutting down due to request from service.");
                                    Application.CurrentInstance.Close();
                                    break;
                                case IPCCommands.CloseConnection:
                                    //exit this connection
                                    Logger.ReportInfo("Service requested we stop listening.");
                                    process = false;
                                    break;

                            }
                            pipe.Disconnect();
                        }
                        catch (IOException e)
                        {
                            Logger.ReportException("Error in MBService connection", e);
                        }
                    }
                    pipe.Close();
                    connected = false;
                }
            });
        }
예제 #8
0
        public static void createPipeServer()
        {
            Decoder decoder = Encoding.Default.GetDecoder();
            Byte[] bytes = new Byte[BufferSize];
            char[] chars = new char[BufferSize];
            int numBytes = 0;
            StringBuilder msg = new StringBuilder();

            try
            {
                pipeServer = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous);
                while (true)
                {
                    pipeServer.WaitForConnection();

                    do
                    {
                        msg.Length = 0;
                        do
                        {
                            numBytes = pipeServer.Read(bytes, 0, BufferSize);
                            if (numBytes > 0)
                            {
                                int numChars = decoder.GetCharCount(bytes, 0, numBytes);
                                decoder.GetChars(bytes, 0, numBytes, chars, 0, false);
                                msg.Append(chars, 0, numChars);
                            }
                        } while (numBytes > 0 && !pipeServer.IsMessageComplete);
                        decoder.Reset();
                        if (numBytes > 0)
                        {
                            //Notify the UI for message received
                            if (owner != null)
                                owner.Dispatcher.Invoke(DispatcherPriority.Send, new Action<string>(owner.OnMessageReceived), msg.ToString());
                            //ownerInvoker.Invoke(msg.ToString());
                        }
                    } while (numBytes != 0);
                    pipeServer.Disconnect();
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
예제 #9
0
        //server
        private void Listen(NamedPipeServerStream server, StreamWriter writer)
        {
            var buffer = new byte[4096];

            #region
            //server.BeginRead(buffer, 0, 4096, p =>
            //{
            //    Trace.WriteLine(p.IsCompleted);
            //    server.EndRead(p);
            //    var reader = new StreamReader(server);
            //    var temp = string.Empty;

            //    while (!string.IsNullOrEmpty((temp = reader.ReadLine())))
            //    {
            //        Trace.WriteLine("Server:from client " + temp);
            //        writer.WriteLine("echo:" + temp);
            //        writer.Flush();
            //        break;
            //    }
            //    server.Disconnect();
            //    Listen(server, writer);
            //}, null);
            #endregion

            server.BeginWaitForConnection(new AsyncCallback(o =>
            {
                var pipe = o.AsyncState as NamedPipeServerStream;
                pipe.EndWaitForConnection(o);

                var reader = new StreamReader(pipe);
                var result = reader.ReadLine();
                var text = string.Format("connected:receive from client {0}|{1}", result.Length, result);
                Trace.WriteLine(text);
                writer.WriteLine(result);
                writer.Flush();
                writer.WriteLine("End");
                writer.Flush();

                server.WaitForPipeDrain();
                server.Disconnect();
                Listen(pipe, writer);
            }), server);
        }
예제 #10
0
        static void Main()
        {
            string echo = "";
            while (true)
            {
                //Create pipe instance
                NamedPipeServerStream pipeServer =
                new NamedPipeServerStream("testpipe", PipeDirection.InOut, 4);
                Console.WriteLine("[ECHO DAEMON] NamedPipeServerStream thread created.");

                //wait for connection
                Console.WriteLine("[ECHO DAEMON] Wait for a client to connect");
                pipeServer.WaitForConnection();

                Console.WriteLine("[ECHO DAEMON] Client connected.");
                try
                {
                    // Stream for the request.
                    StreamReader sr = new StreamReader(pipeServer);
                    // Stream for the response.
                    StreamWriter sw = new StreamWriter(pipeServer);
                    sw.AutoFlush = true;

                    // Read request from the stream.
                     echo = sr.ReadLine();

                    Console.WriteLine("[ECHO DAEMON] Request message: " + echo);

                    // Write response to the stream.
                    sw.WriteLine("[ECHO]: " + echo);

                    pipeServer.Disconnect();
                }
                catch (IOException e)
                {
                    Console.WriteLine("[ECHO DAEMON]ERROR: {0}", e.Message);
                }

                System.IO.File.WriteAllText(@"C:\Users\tlewis\Desktop\WriteLines.txt", echo);

                pipeServer.Close();
            }
        }
        static void Main(string[] args)
        {
            while (true)
            {
                //Create pipe instance
                NamedPipeServerStream pipeServer =
                new NamedPipeServerStream("mojotestpipe", PipeDirection.InOut, 4);
                Console.WriteLine(String.Format("[DOTNET] {0} NamedPipeServerStream thread created.", DateTime.Now.ToString("T")));

                //wait for connection
                Console.WriteLine(String.Format("[DOTNET] {0} Wait for a client to connect...", DateTime.Now.ToString("T")));
                pipeServer.WaitForConnection();

                Console.WriteLine(String.Format("[DOTNET] {0} Client connected.", DateTime.Now.ToString("T")));
                try
                {
                    // Stream for the request.
                    StreamReader sr = new StreamReader(pipeServer);
                    // Stream for the response.
                    StreamWriter sw = new StreamWriter(pipeServer);
                    sw.AutoFlush = true;

                    // Read request from the stream.
                    string echo = sr.ReadLine();

                    Console.WriteLine(String.Format("[DOTNET] {0} Request message: {1}", DateTime.Now.ToString("T"), echo));

                    // Write response to the stream.
                    sw.WriteLine("[ECHO]: " + echo);

                    pipeServer.Disconnect();
                }
                catch (IOException e)
                {
                    Console.WriteLine(String.Format("[DOTNET] {0} Error: {1}", DateTime.Now.ToString("T"), e.Message));
                }
                pipeServer.Close();
            }
        }
예제 #12
0
        void pipeServerThread(object o)
        {
            NamedPipeServerStream pipeServer = null;
            try
            {
                while (true)
                {
                    pipeServer = new NamedPipeServerStream(
                        this.ServerName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);

                    IAsyncResult async = pipeServer.BeginWaitForConnection(null, null);
                    int index = WaitHandle.WaitAny(new WaitHandle[] { async.AsyncWaitHandle, closeApplicationEvent });
                    switch (index)
                    {
                        case 0:
                            pipeServer.EndWaitForConnection(async);
                            using (StreamReader sr = new StreamReader(pipeServer))
                            using (StreamWriter sw = new StreamWriter(pipeServer))
                            {
                                this.Recived(this, new ServerReciveEventArgs(sr, sw));
                            }
                            if (pipeServer.IsConnected)
                            {
                                pipeServer.Disconnect();
                            }
                            break;
                        case 1:
                            return;
                    }
                }
            }
            finally
            {
                if (pipeServer != null)
                {
                    pipeServer.Close();
                }
            }
        }
예제 #13
0
파일: PipeServer.cs 프로젝트: humanosc/Work
        private void pipeWorker ()
        {
            _isRunning = true;
            
            try
            {
                using ( NamedPipeServerStream pipeServer = new NamedPipeServerStream( _pipeName, PipeDirection.In, 4 ) )
                {                     
                    using ( StreamReader reader = new StreamReader( pipeServer ) )
                    {                   
                        while ( true )
                        {
                            if ( _shutDownServer.WaitOne( 500 ) )
                            {
                                break;
                            }

                            pipeServer.WaitForConnection();

                            onMessageReceived( new PipeServerEventArgs( reader.ReadLine(), null ) );

                            pipeServer.Disconnect();
                        }
                    }
                }
            }
            catch ( Exception ex )
            {
                if(!(ex is ThreadAbortException))
                {
                onMessageReceived(new PipeServerEventArgs(null, ex));
                }
            }
            finally
            {
                _isRunning = false;
                _shutDownServerCompleted.Set();
            }
        }
예제 #14
0
        public void StartPipeServer()
        {
            serverStream = new NamedPipeServerStream("zjlrcpipe",
                PipeDirection.InOut,
                10,
                PipeTransmissionMode.Message,
                PipeOptions.None);
            serverStream.ReadMode = PipeTransmissionMode.Message;
            Byte[] bytes = new Byte[1024];
            UTF8Encoding encoding = new UTF8Encoding();
            int numBytes;
            while (running)
            {

                serverStream.WaitForConnection();
                string message = "";
                do
                {
                    numBytes = serverStream.Read(bytes, 0, bytes.Length);

                    message += encoding.GetString(bytes, 0, numBytes);
                } while (!serverStream.IsMessageComplete);

                string[] pas = message.Split('|');
                if (null != pas && pas.Length >= 3)
                {
                    if (!(pas[0] == "exit" && pas[1] == "exit" && pas[2] == "exit"))
                        main.Dispatcher.Invoke(main.searchLrcByZLP, pas[0], pas[1], pas[2]);
                    else
                        running = false;
                }

                serverStream.Disconnect();

            }
            serverStream.Dispose();
        }
예제 #15
0
 public PipeListener(string pipeName, ISafeCollection<TimePlan> timePlans)
 {
     _timePlans = timePlans;
     _pipeServer = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Message);
     Task.Run(() =>
     {
         while (true)
         {
             _pipeServer.WaitForConnection();
             using (StreamReader reader = new StreamReader(_pipeServer))
             {
                 using (StreamWriter writer = new StreamWriter(_pipeServer))
                 {
                     try
                     {
                         var req = JsonConvert.DeserializeObject<NewPipeRequest>(reader.ReadToEnd());
                         string[] names = new string[req.RequestPipeCount];//偷懒
                         for (uint i = 0; i < req.RequestPipeCount; i++)
                         {
                             names[i] = Guid.NewGuid().ToString();
                             var instServer = new NamedPipeServerStream(names[i]);
                             OnAttachServer(instServer);
                         }
                     }
                     catch (Exception)
                     {
                         writer.Write(new NewPipePostBack(null).ToJson());
                     }
                     finally
                     {
                         _pipeServer.Disconnect();
                     }
                 }
             }
         }
     });
 }
예제 #16
0
        public static Task BeginServerListen(string pipeName, NamedPipeChannelReceiveMessage onMessageReceived)
        {
            if (string.IsNullOrEmpty(pipeName)) { throw new ArgumentNullException("pipeName");}
            if (onMessageReceived == null) { throw new ArgumentNullException("onMessageReceived");}

            return Task.Run(() =>
            {
                try
                {
                    using (var pipeServer = new NamedPipeServerStream(pipeName, PipeDirection.In))
                    {
                        while (true)
                        {
                            try
                            {
                                pipeServer.WaitForConnection();
                                var reader = new StreamReader(pipeServer);

                                string message = reader.ReadToEnd();
                                pipeServer.Disconnect();

                                Task.Run(() => onMessageReceived(pipeName, message));
                            }
                            catch (Exception exc)
                            {
                                Log.Debug(string.Format("Receiving message on: {0}", pipeName), exc);
                            }
                        }
                    }
                }
                catch (Exception exc)
                {
                    Log.Error(string.Format("Setting up server: {0}", pipeName), exc);
                }
            });
        }
예제 #17
0
 public ShellCommandHandler(CommandHandler cmdHandler)
 {
     pipeServer = new NamedPipeServerStream("sciGitPipe", PipeDirection.In, 1, PipeTransmissionMode.Byte,
                                      PipeOptions.Asynchronous);
       pipeThread = new Thread(() => {
     while (true) {
       try {
     var ar = pipeServer.BeginWaitForConnection(null, null);
     pipeServer.EndWaitForConnection(ar);
     var ss = new StreamString(pipeServer);
     string verb = ss.ReadString();
     string filename = ss.ReadString();
     cmdHandler(verb, filename);
     pipeServer.Disconnect();
       } catch (ObjectDisposedException) {
     break;
       } catch (IOException) {
     break;
       } catch (Exception e) {
     Logger.LogException(e);
       }
     }
       });
 }
예제 #18
0
 public static void createPipeServer()
 {
     Decoder decoder = Encoding.Default.GetDecoder();
     Byte[] bytes = new Byte[BufferSize];
     char[] chars = new char[BufferSize];
     int numBytes = 0;
     StringBuilder msg = new StringBuilder();
     ownerInvoker = new Invoker(owner);
     ownerInvoker.sDel = ExecuteCommand;
     pipeName = "BarcodeServer";
     try
     {
         pipeServer = new NamedPipeServerStream(pipeName, PipeDirection.In, 1,
                                                PipeTransmissionMode.Message,
                                                PipeOptions.Asynchronous);
         while (true)
         {
             pipeServer.WaitForConnection();
             do
             {
                 msg.Length = 0;
                 do
                 {
                     numBytes = pipeServer.Read(bytes, 0, BufferSize);
                     if (numBytes > 0)
                     {
                         int numChars = decoder.GetCharCount(bytes, 0, numBytes);
                         decoder.GetChars(bytes, 0, numBytes, chars, 0, false);
                         msg.Append(chars, 0, numChars);
                     }
                 } while (numBytes > 0 && !pipeServer.IsMessageComplete);
                 decoder.Reset();
                 if (numBytes > 0)
                 {
                     ownerInvoker.Invoke(msg.ToString());
                 }
             } while (numBytes != 0);
             pipeServer.Disconnect();
         }
     }
     catch (Exception)
     {
         //throw new Exception("Failed to create pipeServer! the detailed messages are: " + ex.Message);
         //MessageBox.Show(ex.Message);
     }
 }
예제 #19
0
        private async Task PrivateRunAsync(CancellationToken cancellationToken)
        {
            using (var pipe = new NamedPipeServerStream(ServerInfo.Name, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
            {
                while (!cancellationToken.IsCancellationRequested)
                {
                    await pipe.WaitForConnectionAsync(cancellationToken);

                    using (var reader = new NonClosingStreamReader(pipe))
                    using (var writer = new NonClosingStreamWriter(pipe) { AutoFlush = true })
                    {
                        var input = await reader.ReadCommandAsync();

                        _log.Information("Retrieved input {Input}", input);

                        switch (input)
                        {
                            case NamedPipeCommand.FindRepo:
                                await writer.WriteAsync(NamedPipeCommand.Ready);
                                await FindRepo(writer, await reader.ReadLineAsync(), cancellationToken);
                                break;
                            case NamedPipeCommand.GetAllRepos:
                                await writer.WriteAsync(NamedPipeCommand.Ready);
                                await GetAllRepos(writer, cancellationToken);
                                break;
                            case NamedPipeCommand.RemoveRepo:
                                await writer.WriteAsync(NamedPipeCommand.Ready);
                                await RemoveRepo(writer, reader, cancellationToken);
                                break;
                            case NamedPipeCommand.ClearCache:
                                await writer.WriteAsync(NamedPipeCommand.Ready);
                                await ProcessClearCacheAsync(writer, cancellationToken);
                                break;
                            case NamedPipeCommand.ExpandGitCommand:
                                await writer.WriteAsync(NamedPipeCommand.Ready);
                                await ProcessExpandGitCommandAsync(writer, reader, cancellationToken);
                                break;
                            default:
                                await writer.WriteAsync(NamedPipeCommand.BadCommand);
                                break;
                        }
                    }

                    // This must be after the reader and writer are closed
                    // Otherwise, an InvalidOperationException is thrown
                    pipe.WaitForPipeDrain();
                    pipe.Disconnect();
                }
            }
        }
예제 #20
0
        private void ServerThreadRoutine(object data)
        {
            string defaultTimeOutValuestring = TimeOutValuestring;
            TvBusinessLayer layer = new TvBusinessLayer();
            Setting setting = null;

            while (PipeServerActive)
            {
                try
                {
                    var sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
                    var rule = new PipeAccessRule(sid, PipeAccessRights.ReadWrite,System.Security.AccessControl.AccessControlType.Allow);
                    var sec = new PipeSecurity();
                    sec.AddAccessRule(rule);

#if (MPTV2)
                    string pipeName = "MP2TvWishListPipe";
#else
                    string pipeName = "TvWishListPipe";
#endif

                    pipeServer = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0, sec);  //only 1 thread for pipe

                    int threadId = Thread.CurrentThread.ManagedThreadId;

                    // Wait for a client to connect
                    Logdebug("TvServer: Waiting for client to connect");
                    PipeServerBusy = false;

                    pipeServer.WaitForConnection();
                    ServerMessage = string.Empty;
                    Logdebug("Client connected on pipe server thread.");
                    PipeServerBusy = true; ;
                    // Read the request from the client. Once the client has
                    // written to the pipe its security token will be available.

                    //pipeServer.ReadTimeout = 5000; //timeout not supported for async streams

                    StreamString ss = new StreamString(pipeServer);

                    // Verify our identity to the connected client using a
                    // string that the client anticipates.


                    MessageFromClient = ss.ReadString();            //receive message from client first
                    //labelreceivedTextServer.Text = messagefromclient;
                    Logdebug("***** CLIENTMESSAGE=" + MessageFromClient);

                    //*******************************
                    //commandinterpretation 
                    //*******************************
                    if (MessageFromClient == PipeCommands.RequestTvVersion.ToString())
                    {
                        string response = PipeCommands.RequestTvVersion.ToString() + "=" + this.Version;
                        Logdebug("sending response " + response);
                        ss.WriteString(response);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.StartEpg.ToString()) == true)
                    {
                        defaultTimeOutValuestring = TimeOutValuestring;
                        string[] tokens = MessageFromClient.Split(':');
                        if (tokens.Length > 1)
                        {
                            TimeOutValuestring = tokens[1];
                            Logdebug("Changed TimeOutValuestring=" + TimeOutValuestring);
                        }
                        Logdebug("Starting EPG Search from pipe command");
                        Thread StartEPGsearchThread = new Thread(StartEPGsearchCommand);
                        StartEPGsearchThread.Start();
                        

                        while ((ServerMessage.StartsWith(PipeCommands.Ready.ToString())==false) && (ServerMessage.StartsWith(PipeCommands.Error.ToString()) == false))
                        {
                            ServerTimeOutCounter = new Thread(ServerTimeOutError);
                            ServerTimeOutCounter.Start();
                            while ((NewServerMessage == false) || (ServerMessage==string.Empty))
                            {
                                Thread.Sleep(500);
                                Logdebug("waiting for new servermessage (ServerMessage="+ServerMessage);
                            }
                            Logdebug("Sending Servermessage=" + ServerMessage);
                            ss.WriteString(ServerMessage);                   //send response messages until done
                            ServerTimeOutCounter.Abort();
                            NewServerMessage = false;
                        }
                        TimeOutValuestring = defaultTimeOutValuestring;
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.Error_TimeOut.ToString()) == true)
                    {
                        TimeOutValuestring = MessageFromClient.Replace(PipeCommands.Error_TimeOut.ToString(), string.Empty);
                        Logdebug("new TimeOutValuestring="+TimeOutValuestring);
                        ss.WriteString(TimeOutValuestring);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ExportTvWishes.ToString()) == true)
                    {
                        defaultTimeOutValuestring = TimeOutValuestring;

                        string[] tokens = MessageFromClient.Split(':');
                        if (tokens.Length > 1)
                        {
                            TimeOutValuestring = tokens[1];
                            Log.Debug("Changed TimeOutValuestring=" + TimeOutValuestring);
                        }

                        if (MessageFromClient.Contains("VIEWONLY=TRUE") == true)
                        {
                            ServerMessage = ExportTvWishes(true);
                        }
                        else //Email & Record Mode
                        {
                            ServerMessage = ExportTvWishes(false);
                        }

                        ss.WriteString(ServerMessage);

                        TimeOutValuestring = defaultTimeOutValuestring;
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ImportTvWishes.ToString()) == true)
                    {
                        defaultTimeOutValuestring = TimeOutValuestring;

                        string[] tokens = MessageFromClient.Split(':');
                        if (tokens.Length > 1)
                        {
                            TimeOutValuestring = tokens[1];
                            Logdebug("Changed TimeOutValuestring=" + TimeOutValuestring);
                        }

                        if (MessageFromClient.Contains("VIEWONLY=TRUE") == true)
                        {
                            ServerMessage = ImportTvWishes(true);
                        }
                        else //Email & Record Mode
                        {
                            ServerMessage = ImportTvWishes(false);
                        }

                        ss.WriteString(ServerMessage);

                        TimeOutValuestring = defaultTimeOutValuestring;
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.RemoveSetting.ToString()) == true)
                    {
                        defaultTimeOutValuestring = TimeOutValuestring;

                        string[] tokens = MessageFromClient.Split(':');
                        if (tokens.Length > 1)
                        {
                            TimeOutValuestring = tokens[1];
                            Logdebug("Changed TimeOutValuestring=" + TimeOutValuestring);
                        }

                        string tag = tokens[0].Replace(PipeCommands.RemoveSetting.ToString(), string.Empty);

                        
                        setting = layer.GetSetting(tag, string.Empty);
                        if (setting != null)
                        {
                            setting.Remove();
                            ServerMessage = "Setting " + tag + " removed";
                            Logdebug("Setting " + tag + " removed");
                        }
                        else
                        {
                            ServerMessage = "Setting " + tag + " could not be removed";
                            Logdebug("Eror: Setting " + tag + " could not be removed");
                 
                        }

                        ss.WriteString(ServerMessage);
                        TimeOutValuestring = defaultTimeOutValuestring;
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.RemoveRecording.ToString()) == true)
                    {//string command = Main_GUI.PipeCommands.RemoveRecording.ToString() + this.IdRecording.ToString() + ":10";
                        defaultTimeOutValuestring = TimeOutValuestring;

                        string[] tokens = MessageFromClient.Split(':');
                        if (tokens.Length > 1)
                        {
                            TimeOutValuestring = tokens[1];
                            Logdebug("Changed TimeOutValuestring=" + TimeOutValuestring);
                        }

                        string idRecordingString = tokens[0].Replace(PipeCommands.RemoveRecording.ToString(), string.Empty);
                        try
                        {
                            int idRecording = -1;
                            int.TryParse(idRecordingString, out idRecording);
                            Logdebug("idRecording=" + idRecording.ToString());
                            Recording myrecording = Recording.Retrieve(idRecording);
                            Logdebug("idRecording=" + myrecording.Title.ToString());
                            myrecording.Delete();
                            Logdebug("Recording deleted");
                            ServerMessage = "Recording deleted"; 
                        }
                        catch (Exception exc)
                        {
                            Logdebug("no recording found for idRecordingString = " + idRecordingString);
                            Logdebug("exception is " + exc.Message);
                            ServerMessage = "Error: Recording could not be deleted check the tvserver log file"; 
                        }

                        ss.WriteString(ServerMessage);
                        TimeOutValuestring = defaultTimeOutValuestring;
                    }
                    
                    else if (MessageFromClient.StartsWith(PipeCommands.RemoveLongSetting.ToString()) == true)
                    {
                        defaultTimeOutValuestring = TimeOutValuestring;

                        string[] tokens = MessageFromClient.Split(':');
                        if (tokens.Length > 1)
                        {
                            TimeOutValuestring = tokens[1];
                            Logdebug("Changed TimeOutValuestring=" + TimeOutValuestring);
                        }

                        //processing
                        string mysetting = string.Empty;
                        try
                        {
                            //cleanup work
                            mysetting = tokens[0].Replace(PipeCommands.RemoveLongSetting.ToString(), string.Empty);
                            Log.Debug("mysetting=" + mysetting);
                            for (int i = 1; i < 1000; i++)
                            {
                                setting = layer.GetSetting(mysetting + "_" + i.ToString("D3"), "_DOES_NOT_EXIST_");
                                Log.Debug("save_longsetting setting=" + setting.Value);
                                if (setting.Value == "_DOES_NOT_EXIST_")
                                {
                                    setting.Remove();
                                    break;
                                }
                                else
                                {
                                    string value = setting.Value;
                                    setting.Remove();

                                }
                            }
                            ServerMessage = "Long setting could be removed";
                        }
                        catch (Exception exc)
                        {
                            Logdebug("Longsetting could not be removed for mysetting= " + mysetting);
                            Logdebug("exception is " + exc.Message);
                            ServerMessage = "Error: Long setting could not be removed - check the tvserver log file";
                        }

                        ss.WriteString(ServerMessage);
                        TimeOutValuestring = defaultTimeOutValuestring;
                    }
#if (MPTV2)
                    else if (MessageFromClient.StartsWith(PipeCommands.WriteSetting.ToString()) == true)
                    {
                        string tag = MessageFromClient.Replace(PipeCommands.WriteSetting.ToString(), string.Empty);
                        string[] tags = tag.Split('\n');
                        ServiceAgents.Instance.SettingServiceAgent.SaveValue(tags[0], tags[1]);

                        ServerMessage = "SUCCESS";
                        ss.WriteString(ServerMessage);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadSetting.ToString()) == true)
                    {
                        string tag = MessageFromClient.Replace(PipeCommands.ReadSetting.ToString(), string.Empty);
                        Log.Debug("tag="+tag);
                        string value = ServiceAgents.Instance.SettingServiceAgent.GetValue(tag, string.Empty);
                        Log.Debug("value=" + value);
                        ServerMessage = value;
                        ss.WriteString(ServerMessage);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadAllCards.ToString()) == true)
                    {
                        defaultTimeOutValuestring = TimeOutValuestring;

                        string[] tokens = MessageFromClient.Split(':');
                        if (tokens.Length > 1)
                        {
                            TimeOutValuestring = tokens[1];
                            Logdebug("Changed TimeOutValuestring=" + TimeOutValuestring);
                        }

                        ServerMessage = string.Empty;
                        foreach (Card mycard in Card.ListAll())
                        {
                            ServerMessage += mycard.IdCard.ToString() + "\n" + mycard.Name + "\n";
                        }
                        //65000 max chars                        
                        ss.WriteString(ServerMessage);
                    }                  
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadAllChannelsByGroup.ToString()) == true)
                    {
                        string groupIdString = MessageFromClient.Replace(PipeCommands.ReadAllChannelsByGroup.ToString(), string.Empty);
                        Log.Debug("groupIdString="+groupIdString);
                        int groupId = -1;
                        int.TryParse(groupIdString, out groupId);
                        Log.Debug("groupId=" + groupId.ToString());

                        ServerMessage = string.Empty;
                        foreach (Channel mychannel in Channel.ListAllByGroup(groupId))
                        {
                            ServerMessage += mychannel.IdChannel.ToString() + "\n" + mychannel.DisplayName + "\n";
                        }
                        Log.Debug("Groupchannels=" + ServerMessage);
                        //65000 max chars                        
                        ss.WriteString(ServerMessage);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadAllChannels.ToString()) == true)//must be after ReadAllChannelsByGroup
                    {
                        ServerMessage = string.Empty;
                        foreach (Channel mychannel in Channel.ListAll())
                        {
                            ServerMessage += mychannel.IdChannel.ToString() + "\n" + mychannel.DisplayName + "\n";
                        }
                        //65000 max chars                        
                        ss.WriteString(ServerMessage);
                    }
                    
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadAllRadioChannelsByGroup.ToString()) == true)
                    {
                        string groupIdString = MessageFromClient.Replace(PipeCommands.ReadAllRadioChannelsByGroup.ToString(), string.Empty);
                        Log.Debug("radiogroupIdString=" + groupIdString);
                        int groupId = -1;
                        int.TryParse(groupIdString, out groupId);
                        Log.Debug("radiogroupId=" + groupId.ToString());

                        ServerMessage = string.Empty;
                        foreach (RadioChannel myradiochannel in RadioChannel.ListAllByGroup(groupId))
                        {
                            ServerMessage += myradiochannel.Id.ToString() + "\n" + myradiochannel.Name + "\n";
                        }
                        Log.Debug("radioGroupchannels=" + ServerMessage);
                        //65000 max chars                        
                        ss.WriteString(ServerMessage);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadAllRadioChannels.ToString()) == true)//must be after ReadAllRadioChannelsByGroup
                    {
                        ServerMessage = string.Empty;
                        foreach (RadioChannel myradiochannel in RadioChannel.ListAll())
                        {
                            ServerMessage += myradiochannel.Id.ToString() + "\n" + myradiochannel.Name + "\n";
                        }
                        //65000 max chars                        
                        ss.WriteString(ServerMessage);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadAllChannelGroups.ToString()) == true)
                    {
                        ServerMessage = string.Empty;
                        foreach (ChannelGroup mygroup in ChannelGroup.ListAll())
                        {
                            ServerMessage += mygroup.Id.ToString() + "\n" + mygroup.GroupName + "\n";
                        }
                        //65000 max chars                        
                        ss.WriteString(ServerMessage);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadAllRadioChannelGroups.ToString()) == true)
                    {
                        ServerMessage = string.Empty;
                        foreach (RadioChannelGroup myradiogroup in RadioChannelGroup.ListAll())
                        {
                            ServerMessage += myradiogroup.Id.ToString() + "\n" + myradiogroup.GroupName + "\n";
                        }
                        //65000 max chars                        
                        ss.WriteString(ServerMessage);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadAllRecordings.ToString()) == true)
                    {
                        ServerMessage = string.Empty;
                        foreach (Recording myrecording in Recording.ListAll())
                        {
                            ServerMessage += myrecording.IdRecording.ToString() + "\n" + myrecording.Title + "\n"+myrecording.FileName + "\n" +
                                             myrecording.IdChannel.ToString() + "\n" + myrecording.StartTime.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture) +
                                             "\n" + myrecording.EndTime.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture) + "\n";
                        }
                        //65000 max chars                        
                        ss.WriteString(ServerMessage);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadAllSchedules.ToString()) == true)
                    {
                        ServerMessage = string.Empty;
                        foreach (Schedule myschedule in Schedule.ListAll())
                        {
                            ServerMessage += myschedule.IdSchedule.ToString() + "\n" + myschedule.ProgramName + "\n" + 
                                             myschedule.IdChannel.ToString() + "\n" + myschedule.StartTime.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture) +
                                             "\n" + myschedule.EndTime.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture) + "\n" +
                                             myschedule.ScheduleType.ToString() + "\n" + myschedule.PreRecordInterval.ToString() + "\n" +
                                             myschedule.PostRecordInterval.ToString() + "\n" + myschedule.MaxAirings.ToString() + "\n" +
                                             myschedule.KeepDate.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture) + "\n" +
                                             myschedule.KeepMethod.ToString() + "\n" + myschedule.Priority.ToString() + "\n" +
                                             myschedule.PreRecordInterval.ToString() + "\n" + myschedule.Series.ToString() + "\n";
                        }
                        //65000 max chars                        
                        ss.WriteString(ServerMessage);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ScheduleDelete.ToString()) == true)
                    {
                        string scheduleIdString = MessageFromClient.Replace(PipeCommands.ScheduleDelete.ToString(), string.Empty);
                        Log.Debug("scheduleIdString=" + scheduleIdString);
                        int scheduleId = -1;
                        int.TryParse(scheduleIdString, out scheduleId);
                        Log.Debug("scheduleId=" + scheduleId.ToString());
                        Schedule.Delete(scheduleId);
                        
                        //65000 max chars                        
                        ss.WriteString("Deleted");
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ScheduleNew.ToString()) == true)
                    {
                        string schedule = MessageFromClient.Replace(PipeCommands.ScheduleNew.ToString(), string.Empty);
                        string[] scheduletags = schedule.Split('\n');

                        int idChannel = -1;
                        int.TryParse(scheduletags[1], out idChannel);
                        DateTime start = DateTime.ParseExact(scheduletags[2], "yyyy-MM-dd_HH:mm", System.Globalization.CultureInfo.InvariantCulture);
                        DateTime end = DateTime.ParseExact(scheduletags[3], "yyyy-MM-dd_HH:mm", System.Globalization.CultureInfo.InvariantCulture);

                        Schedule myschedule = new Schedule(idChannel, scheduletags[0], start, end);
                        myschedule.Persist();
                        

                        ServerMessage = "SUCCESS";
                        ss.WriteString(ServerMessage);
                    }

#endif

                    else //Unknown command
                    {
                        Logdebug("sending response " + PipeCommands.UnknownCommand.ToString());
                        ss.WriteString(PipeCommands.UnknownCommand.ToString());
                    }
                    
                }
                // Catch the IOException that is raised if the pipe is broken
                // or disconnected.
                catch (IOException e)
                {
                    Log.Error("ServerThread ERROR: " + e.Message);
                }
                catch (Exception e)
                {
                    Log.Error("ServerThread ERROR: " + e.Message);
                }

                if (pipeServer != null)
                {
                    if (pipeServer.IsConnected)
                        pipeServer.Disconnect();

                    pipeServer.Close();
                    pipeServer.Dispose();
                    pipeServer = null;
                }
                Logdebug("Connection closed");

            }

            Logdebug("Pipe Server Thread Completed");
        }
        /// <summary>
        /// Listen from service for commands from core or configurator
        /// </summary>
        public static void StartListening()
        {
            if (connected) return; //only one connection...

            Async.Queue("MB Connection", () =>
            {
                System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.BuiltinUsersSid, null);

                PipeSecurity pipeSa = new PipeSecurity();
                pipeSa.SetAccessRule(new PipeAccessRule(sid,
                       PipeAccessRights.ReadWrite, AccessControlType.Allow));

                using (NamedPipeServerStream pipe = new NamedPipeServerStream(MBServiceController.MBSERVICE_IN_PIPE, PipeDirection.In,1,PipeTransmissionMode.Message,PipeOptions.None,1024,1024,pipeSa))
                {
                    connected = true;
                    bool process = true;
                    while (process)
                    {
                        pipe.WaitForConnection(); //wait for the core to tell us something
                        try
                        {
                            // Read the request from the sender.
                            StreamReader sr = new StreamReader(pipe);

                            string command = sr.ReadLine();
                            switch (command.ToLower())
                            {
                                case IPCCommands.ReloadKernel: //don't use this yet - need to figure out how to unload first do a shutdown and restart
                                    //something changed, we need to re-load everything
                                    Logger.ReportInfo("Re-loading kernel due to request from client.");
                                    Kernel.Init(KernelLoadDirective.ShadowPlugins);
                                    break;
                                case IPCCommands.ReloadConfig:
                                    //re-load the main config file
                                    Kernel.Instance.ReLoadConfig();
                                    break;
                                case IPCCommands.Shutdown:
                                    //close Service
                                    Logger.ReportInfo("Shutting down due to request from client.");
                                    MainWindow.Instance.Shutdown();
                                    break;
                                case IPCCommands.Restart:
                                    //restart Service
                                    Logger.ReportInfo("Restarting due to request from client.");
                                    MainWindow.Instance.Restart();
                                    break;
                                case IPCCommands.CancelRefresh:
                                    //cancel any running refresh
                                    MainWindow.Instance.CancelRefresh();
                                    break;
                                case IPCCommands.ForceRebuild:
                                    //force a re-build of the library - used with new version that requires it
                                    Logger.ReportInfo("Forcing re-build of library due to request from client.");
                                    MainWindow.Instance.ForceRebuild();
                                    break;
                                case IPCCommands.Refresh:
                                    Logger.ReportInfo("Refreshing now due to request from client.");
                                    MainWindow.Instance.RefreshNow();
                                    break;
                                case IPCCommands.CloseConnection:
                                    //exit this connection
                                    Logger.ReportInfo("Client requested we stop listening.");
                                    process = false;
                                    break;

                            }
                            pipe.Disconnect();
                        }
                        catch (IOException e)
                        {
                            Logger.ReportException("Error in MB connection", e);
                        }
                    }
                    pipe.Close();
                    connected = false;
                }
            });
        }
예제 #22
0
        public static bool StartListening()
        {
            if (connected) return false; //only one connection...
            if (Application.RunningOnExtender)
            {
                Logger.ReportInfo("Running on an extender.  Not starting client listener.");
                return true; //no comms for extenders
            }

            NamedPipeServerStream pipe;
            try
            {
                pipe = new NamedPipeServerStream(Kernel.MBCLIENT_MUTEX_ID);
            }
            catch (IOException)
            {
                Logger.ReportInfo("Client listener already going - activating that instance of MB...");
                //already started - must be another instance of MB Core - tell it to come to front
                string entryPoint = EntryPointResolver.EntryPointPath;
                if (string.IsNullOrEmpty(entryPoint))
                {
                    SendCommandToCore("activate");
                }
                else //nav to the proper entrypoint
                {
                    Logger.ReportInfo("Navigating current instance to entrypoint " + entryPoint);
                    SendCommandToCore("activateentrypoint," + entryPoint);
                }
                //and exit
                return false;
            }

            connected = true;

            Async.Queue("MBClient Listener", () =>
            {

                bool process = true;
                while (process)
                {
                    pipe.WaitForConnection(); //wait for someone to tell us something
                    string[] commandAndArgs;
                    try
                    {
                        // Read the request from the client.
                        StreamReader sr = new StreamReader(pipe);

                        commandAndArgs = sr.ReadLine().Split(',');
                    }
                    catch (Exception e)
                    {
                        Logger.ReportException("Error during IPC communication.  Attempting to re-start listener", e);
                        try
                        {
                            //be sure we're cleaned up
                            pipe.Disconnect();
                            pipe.Close();
                        }
                        catch
                        { //we don't care if these fail now - and they very well may
                        }
                        finally
                        {
                            connected = false;
                        }
                        StartListening();
                        return;
                    }
                    try
                    {
                        string command = commandAndArgs[0];
                        switch (command.ToLower())
                        {
                            case "play":
                                //request to play something - our argument will be the GUID of the item to play
                                Guid id = new Guid(commandAndArgs[1]);
                                Logger.ReportInfo("Playing ...");
                                //to be implemented...
                                break;
                            case "activateentrypoint":
                                //re-load ourselves and nav to the entrypoint
                                Kernel.Instance.ReLoadRoot();
                                Microsoft.MediaCenter.UI.Application.DeferredInvoke(_ =>
                                {
                                    MediaBrowser.Application.CurrentInstance.LaunchEntryPoint(commandAndArgs[1]);
                                });
                                //and tell MC to navigate to us
                                Microsoft.MediaCenter.Hosting.AddInHost.Current.ApplicationContext.ReturnToApplication();
                                break;
                            case "activate":
                                Logger.ReportInfo("Asked to activate by another process..");
                                //if we were in an entrypoint and we just got told to activate - we need to re-load and go to real root
                                if (Application.CurrentInstance.IsInEntryPoint)
                                {
                                    Kernel.Instance.ReLoadRoot();
                                    Microsoft.MediaCenter.UI.Application.DeferredInvoke(_ =>
                                    {
                                        MediaBrowser.Application.CurrentInstance.LaunchEntryPoint(""); //this will start at root
                                    });
                                }
                                else
                                {
                                    //just need to back up to the root
                                    Application.CurrentInstance.BackToRoot();
                                }

                                // set npv visibility according to current state
                                Application.CurrentInstance.ShowNowPlaying = Application.CurrentInstance.IsPlaying || Application.CurrentInstance.IsExternalWmcApplicationPlaying;

                                //tell MC to navigate to us
                                Microsoft.MediaCenter.Hosting.AddInHost.Current.ApplicationContext.ReturnToApplication();
                                break;
                            case "shutdown":
                                //close MB
                                Logger.ReportInfo("Shutting down due to request from a client (possibly new instance of MB).");
                                Application.CurrentInstance.Close();
                                break;
                            case "closeconnection":
                                //exit this connection
                                Logger.ReportInfo("Service requested we stop listening.");
                                process = false;
                                break;

                        }
                    }
                    catch (Exception e)
                    {
                        Logger.ReportException("Error trying to process IPC command", e);
                    }
                    try
                    {
                        pipe.Disconnect();
                    }
                    catch (Exception e)
                    {
                        Logger.ReportException("Unexpected Error trying to close IPC connection", e);
                    }
                }
                pipe.Close();
                connected = false;
            });
            return true;
        }
        private async void btnStartServer_Click(object sender, EventArgs e)
        {
            try
            {
                btnStartServer.Enabled = false;

                using (NamedPipeServerStream pipe = new NamedPipeServerStream(txtPipeName.Text,
                    PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous))
                {
                    await Task.Factory.FromAsync(pipe.BeginWaitForConnection,
                        pipe.EndWaitForConnection, null);

                    UserToken token = null;

                    if (pipe.IsConnected)
                    {
                        pipe.RunAsClient(() => token = TokenUtils.GetTokenFromThread());
                        pipe.Disconnect();
                    }

                    if (token != null)
                    {
                        TokenForm.OpenForm(token, false);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                btnStartServer.Enabled = true;
            }
        }
예제 #24
0
        void DoListen()
        {
            while (true)
            using (NamedPipeServerStream pipeServer = new NamedPipeServerStream (pipePath, PipeDirection.InOut, numPipeThreads, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, (int)Protocol.MaxMessageLength, (int)Protocol.MaxMessageLength)) {
                Console.WriteLine ("Waiting for client on path " + pipePath);
                pipeServer.WaitForConnection ();

                Console.WriteLine ("Client connected");

                ServerConnection conn;
                if (!AcceptClient (pipeServer, out conn)) {
                    Console.WriteLine ("Client rejected");
                    pipeServer.Disconnect ();
                    continue;
                }

                pipeServer.Flush ();
                pipeServer.WaitForPipeDrain ();

                if (NewConnection != null)
                    NewConnection (conn);

                while (conn.IsConnected)
                    conn.Iterate ();

                pipeServer.Disconnect ();
            }
        }
예제 #25
0
파일: pipes.cs 프로젝트: jarrin/OTM-Client
        private static void startServer(string pn, frm_main f)
        {
            Decoder decoder = Encoding.Default.GetDecoder();
            Byte[] bytes = new Byte[BufferSize];
            char[] chars = new char[BufferSize];
            int numBytes = 0;
            StringBuilder msg = new StringBuilder();
             NamedPipeServerStream pipeServer;
            try
            {
                pipeServer = new NamedPipeServerStream(pn, PipeDirection.In, 1,
                                                       PipeTransmissionMode.Message,
                                                       PipeOptions.Asynchronous);
                while (true)
                {
                    pipeServer.WaitForConnection();

                    do
                    {
                        msg.Length = 0;
                        do
                        {
                            numBytes = pipeServer.Read(bytes, 0, BufferSize);
                            if (numBytes > 0)
                            {
                                int numChars = decoder.GetCharCount(bytes, 0, numBytes);
                                decoder.GetChars(bytes, 0, numBytes, chars, 0, false);
                                msg.Append(chars, 0, numChars);
                            }
                        } while (numBytes > 0 && !pipeServer.IsMessageComplete);
                        decoder.Reset();
                        if (numBytes > 0)
                        {
                            //MESSAGE O
                            string json = msg.ToString();
                            JSONobject a = JsonConvert.DeserializeObject<JSONobject>(json);
                            switch (a.action)
                            {
                                case "dial":
                                    Debug.WriteLine("Call command from namedPipe...");
                                    f.changeState("dialing");
                                    f.setFocus();
                                    f.setNumber(a.data.telnr);
                                    break;
                            }

                            //ownerInvoker.Invoke(msg.ToString());
                        }
                    } while (numBytes != 0);
                    pipeServer.Disconnect();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
예제 #26
0
파일: FindNXT.cs 프로젝트: smo-key/NXTLib
        private void CheckUpdate()
        {
            while (true)
            {
                NamedPipeServerStream pipe = new NamedPipeServerStream("NXTLibTesterGUI_forceupdatepipe", PipeDirection.In);
                pipe.WaitForConnection(); //wait for connection
                StreamReader sr = new StreamReader(pipe);
                if (sr.ReadLine() != "Force Update Now!") { continue; } //read sent bytes
                WriteMessage("Update forced from command line!");
                updatewaiting = true;
                this.Invoke(new MethodInvoker(delegate { CheckUpdateStatus(); }));
                sr.Close();
                sr.Dispose();
                try
                {
                    pipe.Disconnect();
                }
                catch (ObjectDisposedException)
                {

                }
            }
        }
예제 #27
0
        /*
        *METHOD		    :	btn_submit_Click
        *
        *DESCRIPTION	:	used to send the new question to the service when submit clicked
        *
        *PARAMETERS		:	object sender:  Object relaying information on where the event call came from
        *                   EventArgs e:    Object that contains data about the event
        *
        *RETURNS		:	void
        *
        */
        private void btn_submit_Click(object sender, EventArgs e)
        {
            if (txtbx_server.Text.Length > 0 && txtbx_name.Text.Length > 0)
            {
                try
                {
                    userName = txtbx_name.Text;
                    serverName = txtbx_server.Text;
                    //set up the named pipe security
                    PipeSecurity ps = new PipeSecurity();
                    System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
                    PipeAccessRule par = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
                    ps.AddAccessRule(par);

                    //connect to service
                    client = new NamedPipeClientStream(serverName, "ServiceOutgoing");//add server name
                    client.Connect(30);
                    output = new StreamWriter(client);

                    //tell ther service this computers name
                    output.WriteLine(Environment.MachineName);
                    output.Flush();

                    server = new NamedPipeServerStream("UserOutgoing", PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 5000, 5000, ps);
                    server.WaitForConnection();
                    input = new StreamReader(server);

                    //get namedPipe Name
                    pipeName = input.ReadLine();

                    server.Disconnect();
                    server.Dispose();
                    Close();
                }
                catch (Exception)
                {
                    MessageBox.Show("Failed to connect to Server", "Error");
                }
            }
        }
        /// <summary>
        /// Use the pipe classes in the System.IO.Pipes namespace to create the 
        /// named pipe. This solution is recommended.
        /// </summary>
        public static void Run()
        {
            NamedPipeServerStream pipeServer = null;

            try
            {
                // Prepare the security attributes (the pipeSecurity parameter in
                // the constructor of NamedPipeServerStream) for the pipe. This
                // is optional. If pipeSecurity of NamedPipeServerStream is null,
                // the named pipe gets a default security descriptor.and the
                // handle cannot be inherited. The ACLs in the default security
                // descriptor of a pipe grant full control to the LocalSystem
                // account, (elevated) administrators, and the creator owner.
                // They also give only read access to members of the Everyone
                // group and the anonymous account. However, if you want to
                // customize the security permission of the pipe, (e.g. to allow
                // Authenticated Users to read from and write to the pipe), you
                // need to create a PipeSecurity object.
                PipeSecurity pipeSecurity = null;
                pipeSecurity = CreateSystemIOPipeSecurity();

                // Create the named pipe.
                pipeServer = new NamedPipeServerStream(
                    Program.PipeName,               // The unique pipe name.
                    PipeDirection.InOut,            // The pipe is duplex
                    NamedPipeServerStream.MaxAllowedServerInstances,
                    PipeTransmissionMode.Message,   // Message-based communication
                    PipeOptions.None,               // No additional parameters
                    Program.BufferSize,             // Input buffer size
                    Program.BufferSize,             // Output buffer size
                    pipeSecurity,                   // Pipe security attributes
                    HandleInheritability.None       // Not inheritable
                    );
                  Console.WriteLine("The named pipe ({0}) is created.",
                    Program.FullPipeName);

                // Wait for the client to connect.
                Console.WriteLine("Waiting for the client's connection...");
                pipeServer.WaitForConnection();
                Console.WriteLine("Client is connected.");

                //
                // Receive a request from client.
                //
                // Note: The named pipe was created to support message-based
                // communication. This allows a reading process to read
                // varying-length messages precisely as sent by the writing
                // process. In this mode you should not use StreamWriter to write
                // the pipe, or use StreamReader to read the pipe. You can read
                // more about the difference from the article:
                // http://go.microsoft.com/?linkid=9721786.
                //

                string message;

                do
                {
                    byte[] bRequest = new byte[Program.BufferSize];
                    int cbRequest = bRequest.Length, cbRead;

                    cbRead = pipeServer.Read(bRequest, 0, cbRequest);

                    // Unicode-encode the received byte array and trim all the
                    // '\0' characters at the end.
                    message = Encoding.Unicode.GetString(bRequest).TrimEnd('\0');
                    Console.WriteLine("Receive {0} bytes from client: \"{1}\"",
                        cbRead, message);
                }
                while (!pipeServer.IsMessageComplete);

                //
                // Send a response from server to client.
                //
                var proc = new System.Diagnostics.Process
                {
                    StartInfo = new System.Diagnostics.ProcessStartInfo
                    {
                        FileName = message,
                        Arguments = "",
                        UseShellExecute = false,
                        RedirectStandardOutput = true,
                        CreateNoWindow = true
                    }
                };

                proc.Start();
                StringBuilder sb = new StringBuilder();
                while (!proc.StandardOutput.EndOfStream)
                {
                    string line = proc.StandardOutput.ReadLine();
                    // do something with line
                    sb.Append("\n" + line );
                }

                //System.Diagnostics.Process.Start(message);

                sb.Append("###AAA###" + proc.ExitCode + "###BBB###");
                message = sb.ToString();

                //System.Diagnostics.Process.Start("notepad");

                byte[] bResponse = Encoding.Unicode.GetBytes(message);
                int cbResponse = bResponse.Length;

                pipeServer.Write(bResponse, 0, cbResponse);

               // Console.WriteLine("Send {0} bytes to client: \"{1}\"",
                //    cbResponse, message.TrimEnd('\0'));

                // Flush the pipe to allow the client to read the pipe's contents
                // before disconnecting. Then disconnect the client's connection.
                pipeServer.WaitForPipeDrain();
                pipeServer.Disconnect();
            }
            catch (Exception ex)
            {
                Console.WriteLine("The server throws the error: {0}", ex.Message);
            }
            finally
            {
                if (pipeServer != null)
                {
                    pipeServer.Close();
                    pipeServer = null;
                }
            }
        }
예제 #29
0
        public void DoEncode(object sender, DoWorkEventArgs e)
        {
            _bw = (BackgroundWorker)sender;

            string passStr = Processing.GetResourceString("vp8_pass");
            string status = Processing.GetResourceString("vp8_encoding_status");
            string progressFormat = Processing.GetResourceString("vp8_encoding_progress");

            //progress vars
            DateTime startTime = DateTime.Now;
            TimeSpan remaining = new TimeSpan(0, 0, 0);
            // end progress

            VP8Profile encProfile = (VP8Profile)_jobInfo.VideoProfile;

            if (!_jobInfo.EncodingProfile.Deinterlace && _jobInfo.VideoStream.Interlaced)
                _jobInfo.VideoStream.Interlaced = false;

            Size resizeTo = VideoHelper.GetTargetSize(_jobInfo);

            if (string.IsNullOrEmpty(_jobInfo.AviSynthScript))
                GenerateAviSynthScript(resizeTo);

            string inputFile = _jobInfo.AviSynthScript;
            string outFile =
                Processing.CreateTempFile(
                    string.IsNullOrEmpty(_jobInfo.TempOutput) ? _jobInfo.JobName : _jobInfo.TempOutput, "encoded.webm");

            _frameCount = _jobInfo.VideoStream.FrameCount;

            int targetBitrate = 0;
            if (_jobInfo.EncodingProfile.TargetFileSize > 0)
                targetBitrate = Processing.CalculateVideoBitrate(_jobInfo);

            int encodeMode = encProfile.EncodingMode;
            string pass = string.Empty;
            if (encodeMode == 1)
                pass = string.Format(" {1} {0:0}; ", _jobInfo.StreamId, passStr);

            _bw.ReportProgress(-10, status + pass.Replace("; ", string.Empty));
            _bw.ReportProgress(0, status);

            string argument = VP8CommandLineGenerator.Generate(encProfile,
                                                                targetBitrate,
                                                                resizeTo.Width,
                                                                resizeTo.Height,
                                                                _jobInfo.StreamId,
                                                                _jobInfo.VideoStream.FrameRateEnumerator,
                                                                _jobInfo.VideoStream.FrameRateDenominator,
                                                                outFile);

            string localExecutable = Path.Combine(AppSettings.ToolsPath, Executable);

            Regex frameInformation = new Regex(@"^.*Pass\s\d\/\d frame \s*\d*\/(\d*).*$",
                                               RegexOptions.Singleline | RegexOptions.Multiline);

            using (Process encoder = new Process(),
                           decoder = FfMpeg.GenerateDecodeProcess(inputFile))
            {
                ProcessStartInfo parameter = new ProcessStartInfo(localExecutable)
                    {
                        WorkingDirectory = AppSettings.DemuxLocation,
                        Arguments = argument,
                        CreateNoWindow = true,
                        UseShellExecute = false,
                        RedirectStandardError = true,
                        RedirectStandardInput = true
                    };
                encoder.StartInfo = parameter;

                encoder.ErrorDataReceived += (outputSender, outputEvent) =>
                    {
                        string line = outputEvent.Data;

                        if (string.IsNullOrEmpty(line)) return;

                        Match result = frameInformation.Match(line);

                        // ReSharper disable AccessToModifiedClosure
                        TimeSpan eta = DateTime.Now.Subtract(startTime);
                        // ReSharper restore AccessToModifiedClosure
                        long secRemaining = 0;

                        if (result.Success)
                        {
                            long current;
                            Int64.TryParse(result.Groups[1].Value, NumberStyles.Number,
                                           AppSettings.CInfo, out current);
                            long framesRemaining = _frameCount - current;
                            float fps = 0f;
                            if (eta.Seconds != 0)
                            {
                                //Frames per Second
                                double codingFPS = Math.Round(current/eta.TotalSeconds, 2);

                                if (codingFPS > 1)
                                {
                                    secRemaining = framesRemaining/(int) codingFPS;
                                    fps = (float) codingFPS;
                                }
                                else
                                    secRemaining = 0;
                            }

                            if (secRemaining > 0)
                                remaining = new TimeSpan(0, 0, (int) secRemaining);

                            DateTime ticks = new DateTime(eta.Ticks);

                            string progress = string.Format(progressFormat,
                                                            current, _frameCount,
                                                            fps,
                                                            remaining, ticks, pass);
                            _bw.ReportProgress((int) (((float) current/_frameCount)*100),
                                               progress);
                        }
                        else
                        {
                            Log.InfoFormat("vpxenc: {0:s}", line);
                        }
                    };

                Log.InfoFormat("start parameter: vpxenc {0:s}", argument);

                bool started;
                bool decStarted;
                try
                {
                    started = encoder.Start();
                }
                catch (Exception ex)
                {
                    started = false;
                    Log.ErrorFormat("vpxenc exception: {0}", ex);
                    _jobInfo.ExitCode = -1;
                }

                NamedPipeServerStream decodePipe = new NamedPipeServerStream(AppSettings.DecodeNamedPipeName,
                                                                             PipeDirection.In, 1,
                                                                             PipeTransmissionMode.Byte, PipeOptions.None);

                try
                {
                    decStarted = decoder.Start();
                }
                catch (Exception ex)
                {
                    decStarted = false;
                    Log.ErrorFormat("avconv exception: {0}", ex);
                    _jobInfo.ExitCode = -1;
                }

                startTime = DateTime.Now;

                if (started && decStarted)
                {
                    encoder.PriorityClass = AppSettings.GetProcessPriority();
                    encoder.BeginErrorReadLine();
                    decoder.PriorityClass = AppSettings.GetProcessPriority();
                    decoder.BeginErrorReadLine();

                    Thread pipeReadThread = new Thread(() =>
                        {
                            try
                            {
                                ReadThreadStart(decodePipe, encoder);
                            }
                            catch (Exception ex)
                            {
                                Log.Error(ex);
                            }
                        });
                    pipeReadThread.Start();
                    pipeReadThread.Priority = ThreadPriority.BelowNormal;
                    encoder.Exited += (o, args) => pipeReadThread.Abort();

                    while (!encoder.HasExited)
                    {
                        if (_bw.CancellationPending)
                        {
                            encoder.Kill();
                            decoder.Kill();
                        }
                        Thread.Sleep(200);
                    }

                    encoder.WaitForExit(10000);
                    encoder.CancelErrorRead();

                    if (decodePipe.IsConnected)
                        try
                        {
                            decodePipe.Disconnect();
                        }
                        catch (Exception ex)
                        {
                            Log.Error(ex);
                        }

                    try
                    {
                        decodePipe.Close();
                        decodePipe.Dispose();
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex);
                    }

                    decoder.WaitForExit(10000);
                    decoder.CancelErrorRead();

                    _jobInfo.ExitCode = encoder.ExitCode;
                    Log.InfoFormat("Exit Code: {0:g}", _jobInfo.ExitCode);
                }
            }

            if (_jobInfo.ExitCode == 0)
            {
                if ((encProfile.EncodingMode == 1 && _jobInfo.StreamId == 2) ||
                    encProfile.EncodingMode == 0)
                {
                    _jobInfo.VideoStream.Encoded = true;
                    _jobInfo.VideoStream.IsRawStream = false;

                    _jobInfo.TempFiles.Add(_jobInfo.VideoStream.TempFile);
                    _jobInfo.VideoStream.TempFile = outFile;

                    try
                    {
                        _jobInfo.MediaInfo = Processing.GetMediaInfo(_jobInfo.VideoStream.TempFile);
                    }
                    catch (TimeoutException ex)
                    {
                        Log.Error(ex);
                    }
                    _jobInfo.VideoStream = VideoHelper.GetStreamInfo(_jobInfo.MediaInfo, _jobInfo.VideoStream, _jobInfo.EncodingProfile.OutFormat == OutputType.OutputBluRay);

                    string statsFile = Processing.CreateTempFile(outFile, "stats");
                    _jobInfo.TempFiles.Add(statsFile);
                    _jobInfo.TempFiles.Add(_jobInfo.AviSynthScript);
                    _jobInfo.TempFiles.Add(_jobInfo.FfIndexFile);
                    _jobInfo.TempFiles.Add(_jobInfo.AviSynthStereoConfig);
                }
            }

            _bw.ReportProgress(100);
            _jobInfo.CompletedStep = _jobInfo.NextStep;
            e.Result = _jobInfo;
        }
예제 #30
0
        public void ServiceRequest(NamedPipeServerStream nss)
        {
            var msgbuf = new List<byte>(8192);
            var rxbuf = new byte[256 * 1024];
            int count = 0;


            Logging.Emit("reading from client");
            do
            {
                count = nss.Read(rxbuf, msgbuf.Count, rxbuf.Length);
                if (count > 0)
                {
                    msgbuf.AddRange(rxbuf.Take(count));
                }

            } while (!nss.IsMessageComplete);

            Logging.Emit("server read  {0} bytes", msgbuf.Count);

            // deserialize message from msgbuf
            var req = CClashMessage.Deserialize<CClashRequest>(msgbuf.ToArray());
            cache.Setup(); // needed?
            Logging.Emit("processing request");
            var resp = ProcessRequest(req);
            Logging.Emit("request complete: supported={0}, exitcode={1}", resp.supported, resp.exitcode);
            var tx = resp.Serialize();
            nss.Write(tx, 0, tx.Length);
            nss.Flush();
            Logging.Emit("server written {0} bytes", tx.Length);

            nss.WaitForPipeDrain();
            nss.Disconnect();
            
            Logging.Emit("request done");
        }
예제 #31
0
    public static async Task ClientServerOneWayOperations(
        string pipeName, PipeDirection serverDirection,
        bool asyncServerPipe, bool asyncClientPipe,
        bool asyncServerOps, bool asyncClientOps)
    {
        PipeDirection clientDirection = serverDirection == PipeDirection.Out ? PipeDirection.In : PipeDirection.Out;
        PipeOptions serverOptions = asyncServerPipe ? PipeOptions.Asynchronous : PipeOptions.None;
        PipeOptions clientOptions = asyncClientPipe ? PipeOptions.Asynchronous : PipeOptions.None;

        using (NamedPipeServerStream server = new NamedPipeServerStream(pipeName, serverDirection, 1, PipeTransmissionMode.Byte, serverOptions))
        {
            byte[] received = new byte[] { 0 };
            Task clientTask = Task.Run(async () =>
            {
                using (NamedPipeClientStream client = new NamedPipeClientStream(".", pipeName, clientDirection, clientOptions))
                {
                    if (asyncClientOps)
                    {
                        await client.ConnectAsync();
                        if (clientDirection == PipeDirection.In)
                        {
                            received = await ReadBytesAsync(client, sendBytes.Length);
                        }
                        else
                        {
                            await WriteBytesAsync(client, sendBytes);
                        }
                    }
                    else
                    {
                        client.Connect();
                        if (clientDirection == PipeDirection.In)
                        {
                            received = ReadBytes(client, sendBytes.Length);
                        }
                        else
                        {
                            WriteBytes(client, sendBytes);
                        }
                    }
                }
            });

            if (asyncServerOps)
            {
                await server.WaitForConnectionAsync();
                if (serverDirection == PipeDirection.Out)
                {
                    await WriteBytesAsync(server, sendBytes);
                }
                else
                {
                    received = await ReadBytesAsync(server, sendBytes.Length);
                }
            }
            else {
                server.WaitForConnection();
                if (serverDirection == PipeDirection.Out)
                {
                    WriteBytes(server, sendBytes);
                }
                else
                {
                    received = ReadBytes(server, sendBytes.Length);
                }
            }

            await clientTask;
            Assert.Equal(sendBytes, received);

            server.Disconnect();
            Assert.False(server.IsConnected);
        }
    }