Named pipe client. Use this to open the client end of a named pipes created with NamedPipeServerStream.
Inheritance: PipeStream
Beispiel #1
0
 private void ensureOnlyOne()
 {
     var pipeName = $"{this.GetType().FullName}.{winServiceInstaller.ServiceName}";
     try
     {
         var serverStream = createNewNamedPipedServerStream(pipeName);
         AsyncCallback ac = null;
         ac = ar =>
         {
             showForm();
             serverStream.Close();
             serverStream = createNewNamedPipedServerStream(pipeName);
             serverStream.BeginWaitForConnection(ac, null);
         };
         serverStream.BeginWaitForConnection(ac, null);
     }
     catch
     {
         try
         {
             var clientStream = new NamedPipeClientStream(pipeName);
             clientStream.Connect();
             clientStream.Close();
         }
         finally
         {
             this.DialogResult = DialogResult.Cancel;
             this.Close();
             Environment.Exit(0);
         }
     }
 }
Beispiel #2
0
 public ClientDirectStream(string name)
 {
     // this type exists so that consumer doesn't need to care about all these arguments/flags to get good performance
     _name = name;
     _pipe = new NamedPipeClientStream(serverName: ".", pipeName: name, direction: PipeDirection.Out);
     _stream = new BufferedStream(_pipe, BUFFERSIZE);
 }
 static void Main(string[] args)
 {
     if (args.Length < 3)
         return;
     var pipe = new NamedPipeClientStream(args[2].Substring(9, args[2].Length - 9));
     pipe.Connect();
     var reader = new StreamReader(pipe);
     while(true)
     {
         if(reader.ReadLine().StartsWith("c:getPlatforms", StringComparison.InvariantCulture))
         {
             WriteNumber(pipe, -3085);
             WriteNumber(pipe, 0);
             WriteNumber(pipe, 0);
             WriteNumber(pipe, 1);
             WriteNumber(pipe, 0);
             WriteNumber(pipe, 2);
             WriteNumber(pipe, 8);
             WriteNumber(pipe, 1);
             WriteNumber(pipe, 1);
             WriteNumber(pipe, 2);
             WriteNumber(pipe, 10);
             WriteNumber(pipe, 0);
             WriteNumber(pipe, 0);
         }
     }
 }
        public void StartListening(Action<string> messageRecieved)
        {
            Task.Factory.StartNew(() =>
                    {
                        while (true)
                        {
                            try
                            {
                                using (
                                    var pipe = new NamedPipeClientStream(".", "htmlbackground", PipeDirection.In,
                                                                         PipeOptions.Asynchronous))
                                {
                                    pipe.Connect(500);
                                    if (pipe.IsConnected)
                                    {
                                        using (var streamReader = new StreamReader(pipe))
                                        {
                                            var message = streamReader.ReadToEnd();

                                            if (messageRecieved != null)
                                            {
                                                // invoke the message received action
                                                messageRecieved(message);
                                            }
                                        }
                                    }
                                }
                            }
                            catch (TimeoutException)
                            {
                            }
                        }
                    }, TaskCreationOptions.LongRunning);
        }
        static void Main(string[] args)
        {
            using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".",
                                                                                "testpipe",
                                                                                PipeDirection.InOut))
            {

                // Connect to the pipe or wait until the pipe is available.
                Console.Write("Attempting to connect to pipe...");
                pipeClient.Connect();

                Console.WriteLine("Connected to pipe.");
                Console.WriteLine("There are currently {0} pipe server instances open.",
                   pipeClient.NumberOfServerInstances);

                while (pipeClient.IsConnected)
                {
                    using (StreamReader sr = new StreamReader(pipeClient))
                    {
                        // Display the read text to the console
                        string temp;
                        while ((temp = sr.ReadLine()) != null)
                        {
                            Console.WriteLine("Received from server: {0}", temp);
                        }
                    }
                }
            }
            Console.Write("Press Enter to continue...");
            Console.ReadLine();
        }
        public void CheckUnenrolledHostShouldRemoved()
        {
            CredentialReceiver.instance.Init();
            ServerListHelper.instance.Init();
            DatabaseManager.CreateNewConnection(dbName);
            IXenConnection connection = DatabaseManager.ConnectionFor(dbName);
            Session _session = DatabaseManager.ConnectionFor(dbName).Session;
            DatabaseManager.ConnectionFor(dbName).LoadCache(_session);
            Dictionary<string, string> config = cleanStack();
            connection.LoadCache(_session);

            int conSize = ServerListHelper.instance.GetServerList().Count;

            NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", HealthCheckSettings.HEALTH_CHECK_PIPE, PipeDirection.Out);
            pipeClient.Connect();
            string credential = EncryptionUtils.ProtectForLocalMachine(String.Join(SEPARATOR.ToString(), new[] { connection.Hostname, connection.Username, connection.Password }));
            pipeClient.Write(Encoding.UTF8.GetBytes(credential), 0, credential.Length);
            pipeClient.Close();
            System.Threading.Thread.Sleep(1000);
            List<ServerInfo> con = ServerListHelper.instance.GetServerList();
            Assert.IsTrue(con.Count == conSize + 1);


            //1. If XenServer has not enroll, lock will not been set.
            config = cleanStack();
            config[HealthCheckSettings.STATUS] = "false";
            Pool.set_health_check_config(_session, connection.Cache.Pools[0].opaque_ref, config);
            Assert.IsFalse(RequestUploadTask.Request(connection, _session));
            con = ServerListHelper.instance.GetServerList();
            Assert.IsTrue(con.Count == conSize);
            CredentialReceiver.instance.UnInit();
        }
Beispiel #7
0
        public void Connect(string pipeName, string serverName = ".", int timeout = 2000)
        {
            NamedPipeClientStream pipeStream = null;

            try
            {
                pipeStream = new NamedPipeClientStream(serverName, pipeName, PipeDirection.InOut,
                                                       PipeOptions.Asynchronous, TokenImpersonationLevel.Impersonation);
                pipeStream.Connect(timeout);
                using (var stringStream = new StringStream(pipeStream))
                {
                    if (OnConnected != null)
                    {
                        OnConnected(stringStream);
                    }
                }
            }
            catch (Exception exception)
            {
                if (OnErrorOcurred != null)
                {
                    OnErrorOcurred(exception);
                }
            }
            finally
            {
                if (pipeStream != null && pipeStream.IsConnected)
                {
                    pipeStream.Flush();
                    pipeStream.Close();
                }
            }
        }
 public static bool SendCommandToCore(string machine, string command)
 {
     NamedPipeClientStream pipeClient =
         new NamedPipeClientStream(machine, Kernel.MBCLIENT_MUTEX_ID,
         PipeDirection.Out, PipeOptions.None);
     StreamWriter sw = new StreamWriter(pipeClient);
     try
     {
         pipeClient.Connect(2000);
     }
     catch (TimeoutException)
     {
         Logger.ReportWarning("Unable to send command to core (may not be running).");
         return false;
     }
     try
     {
         sw.AutoFlush = true;
         sw.WriteLine(command);
         pipeClient.Flush();
         pipeClient.Close();
     }
     catch (Exception e)
     {
         Logger.ReportException("Error sending commmand to core", e);
         return false;
     }
     return true;
 }
        private void Run()
        {
            foreach (var message in _messages.GetConsumingEnumerable())
            {
                try
                {
                    var pipe = new NamedPipeClientStream(".", _pipeName, PipeDirection.Out, PipeOptions.Asynchronous);

                    try
                    {
                        pipe.Connect(0);
                    }
                    catch (TimeoutException)
                    {
                        continue;
                    }

                    using (var writer = new StreamWriter(pipe))
                    {
                        writer.WriteLine(message);
                    }
                }
                catch (Exception ex)
                {
                    // TODO: Something?
                    continue;
                }
            }
        }
Beispiel #10
0
        public void Start()
        {
            this.serialPort = 
                new SerialPort(
                    CurrentSettings.ComPort, 
                    CurrentSettings.BaudRate, 
                    CurrentSettings.Parity, 
                    CurrentSettings.DataBits,
                    CurrentSettings.StopBits)
                    {
                        RtsEnable = true,
                        DtrEnable = true,
                        Encoding = Encoding.UTF8
                     };

            this.namedPipe = 
                new NamedPipeClientStream(
                    CurrentSettings.MachineName, 
                    CurrentSettings.NamedPipe, 
                    PipeDirection.InOut,
                    PipeOptions.Asynchronous);

            this.portForwarder = new Thread(this.PortForwarder);          
            portForwarder.Start();

            IsStarted = true;
        }
Beispiel #11
0
 private byte[] readMessage(NamedPipeClientStream client)
 {
     byte[] message = new byte[0];
     _offset = 0;
     _current = new List<byte>();
     while (true)
     {
         var i = client.ReadByte();
         if (i == -1)
         {
             _offset = 0;
             return new byte[0];
         }
         if (i == 0)
         {
             var buffer = new byte[_offset];
             Array.Copy(_bytes, buffer, _offset);
             _current.AddRange(buffer);
             message = _current.ToArray();
             _current = new List<byte>();
             _offset = 0;
             break;
         }
         _bytes[_offset] = Convert.ToByte(i);
         _offset++;
         if (_offset == _bytes.Length)
         {
             _current.AddRange(_bytes);
             _offset = 0;
         }
     }
     return message;
 }
 public Sockets(DataTable dtSockets, Main.SockInfo sinfo, NamedPipeClientStream pout)
 {
     int i;
     InitializeComponent();
     pipeOut = pout;
     foreach (DataRow drow in dtSockets.Rows)
     {
         i = dgridSockets.Rows.Add();
         dgridSockets.Rows[i].Cells["socket"].Value = ((int)drow["socket"]).ToString("X4");
         if (drow["proto"].ToString() != String.Empty)
             dgridSockets.Rows[i].Cells["proto"].Value = sinfo.proto((int)drow["proto"]);
         if (drow["fam"].ToString() != String.Empty)
             if (((int)drow["fam"] >= 0) && ((int)drow["fam"] <= sinfo.afamily.Length - 1))
                 dgridSockets.Rows[i].Cells["fam"].Value = sinfo.afamily[(int)drow["fam"]];
         if (drow["type"].ToString() != String.Empty)
             if (((int)drow["type"] >= 0) && ((int)drow["type"] <= sinfo.atype.Length - 1))
                 dgridSockets.Rows[i].Cells["type"].Value = sinfo.atype[(int)drow["type"]];
         if (drow["lastapi"].ToString() != String.Empty)
             dgridSockets.Rows[i].Cells["lastapi"].Value = sinfo.api((int)drow["lastapi"]);
         if (drow["lastmsg"].ToString() != String.Empty)
             dgridSockets.Rows[i].Cells["lastmsg"].Value = sinfo.msg((int) drow["lastmsg"]);
         dgridSockets.Rows[i].Cells["local"].Value = drow["local"].ToString();
         dgridSockets.Rows[i].Cells["remote"].Value = drow["remote"].ToString();
     }
 }
        /// <summary>
        /// Sends message to all remote listeners
        /// </summary>
        /// <param name="data">Message data</param>
        protected override void SendMessage(byte[] data)
        {
            foreach (var pipeConfiguration in _clientPipesConfiguration)
            {
                using (var namedPipeClient = new NamedPipeClientStream(
                    pipeConfiguration.ServerName, pipeConfiguration.Name))
                {
                    try
                    {
                        _log.DebugFormat("Send message to {0}\\{1}",
                            pipeConfiguration.ServerName, pipeConfiguration.Name);

                        if (!ConnectToPipe(namedPipeClient))
                        {
                            _log.WarnFormat("Couldn't connect to pipe {0}\\{1}",
                                pipeConfiguration.ServerName, pipeConfiguration.Name);
                            continue;
                        }

                        namedPipeClient.Write(data, 0, data.Length);
                    }
                    catch (IOException ex)
                    {
                        _log.Warn("Exception while sending a message", ex);
                    }
                }
            }
        }
        private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            var p = UtilityProgram.CallWithAdmin("--download-packages", mod);
            Regex r = new Regex(@"(\d{1,3})% (\d+/\d+ bytes)");

            NamedPipeClientStream pipe = new NamedPipeClientStream(".", "OpenRA.Utility", PipeDirection.In);
            pipe.Connect();

            using (var response = new StreamReader(pipe))
            {
                while (!p.HasExited)
                {
                    string s = response.ReadLine();
                    if (Util.IsError(ref s))
                    {
                        e.Cancel = true;
                        e.Result = s;
                        return;
                    }
                    if (!r.IsMatch(s)) continue;
                    var m = r.Match(s);
                    backgroundWorker1.ReportProgress(int.Parse(m.Groups[1].Value), m.Groups[2].Value);
                }
            }
        }
Beispiel #15
0
        public void Close()
        {
            Console.WriteLine(string.Format("closing pipe server {0}...", PipeName));
            m_closing = true;
            //emulate new client connected to resume listener thread
            using (NamedPipeClientStream fakeClient = new NamedPipeClientStream(".", PipeName, PipeDirection.In))
            {
                try
                {
                    fakeClient.Connect(100);
                    fakeClient.Close();
                }
                catch
                {
                    //server was stopped already
                }
            }
            if (m_listenerThread != null && m_listenerThread.IsAlive)
            {
                if (!m_listenerThread.Join(5000))
                {
                    m_listenerThread.Abort();
                }
            }
            m_listenerThread = null;

            Console.WriteLine(string.Format("disconnecting clients from pipe {0}...", PipeName));
            while (m_pipeStreams.Count > 0)
            {
                DisconnectClient(m_pipeStreams[0]);
            }

            Console.WriteLine(string.Format("Pipe server {0} stopped OK", PipeName));
        }
        /// <summary>
        /// Calls method with one parameter and result. Deserializes parameter and serialize result.
        /// </summary>
        /// <param name="type">Type containing method</param>
        /// <param name="methodName">Name of method to call</param>
        /// <param name="pipeName">Name of pipe to pass parameter and result</param>
        static void InvokeFunc(Type type, string methodName, string pipeName)
        {
            using (var pipe = new NamedPipeClientStream(pipeName))
            {

                pipe.Connect();

                var formatter = new BinaryFormatter();
                ProcessThreadParams pars;
                var lengthBytes = new byte[4];
                pipe.Read(lengthBytes, 0, 4);
                var length = BitConverter.ToInt32(lengthBytes, 0);

                var inmemory = new MemoryStream(length);
                var buf = new byte[1024];
                while (length != 0)
                {
                    var red = pipe.Read(buf, 0, buf.Length);
                    inmemory.Write(buf, 0, red);
                    length -= red;
                }
                inmemory.Position = 0;
                try
                {
                    AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
                      {
                          return type.Assembly;
                      };

                    pars = (ProcessThreadParams)formatter.Deserialize(inmemory);

                    var method = type.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance, null, pars.Types, null);
                    if (method == null) throw new InvalidOperationException("Method is not found: " + methodName);

                    if (pars.Pipe != null)
                    {
                        var auxPipe = new NamedPipeClientStream(pars.Pipe);
                        auxPipe.Connect();

                        for (int i = 0; i < pars.Parameters.Length; i++)
                            if (pars.Parameters[i] is PipeParameter) pars.Parameters[i] = auxPipe;
                    }
                    object result = method.Invoke(pars.Target, pars.Parameters);

                    var outmemory = new MemoryStream();
                    formatter.Serialize(outmemory, ProcessThreadResult.Successeded(result));
                    outmemory.WriteTo(pipe);
                }
                catch (TargetInvocationException e)
                {
                    formatter.Serialize(pipe, ProcessThreadResult.Exception(e.InnerException));
                    throw e.InnerException;
                }
                catch (Exception e)
                {
                    formatter.Serialize(pipe, ProcessThreadResult.Exception(e));
                    throw;
                }
            }
        }
 public override void evaluate()
 {
     try
     {
         if ((bool)pinInfo["trigger"].value.data && lastInput != pinInfo["trigger"].value.data)
         {
             myPipe = new NamedPipeClientStream(".", "lavalamp winamp control", PipeDirection.InOut,
                                                PipeOptions.None);
             myPipe.Connect(500);
             StreamWriter myWriter = new StreamWriter(myPipe);
             myWriter.AutoFlush = true;
             myWriter.Write(Cmd);
             myPipe.Close();
         }
         lastInput = pinInfo["trigger"].value;
     }
     catch (ObjectDisposedException)
     {
         // todo - add option to ignore errors / errored state / etc
         MessageBox.Show("Unable to contact winamp. Is it running? Is the plugin installed OK?");
     }
     catch (IOException)
     {
         // todo - add option to ignore errors / errored state / etc
         MessageBox.Show("Unable to contact winamp. Is it running? Is the plugin installed OK?");
     }
     catch (System.TimeoutException)
     {
         MessageBox.Show("Unable to contact winamp. Is it running? Is the plugin installed OK?");
     }
 }
 public static void SendMessage(String optionVal)
 {
     using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "RipplePipe", PipeDirection.Out, PipeOptions.Asynchronous))
     {
         try
         {
             pipeClient.Connect(2000);
         }
         catch (Exception)
         {
             //Try once more
             try
             {
                 pipeClient.Connect(5000);
             }
             catch (Exception ex)
             {
                 RippleCommonUtilities.LoggingHelper.LogTrace(1, "Went wrong in Send Message at Screen side {0}", ex.Message);
                 return;
             }
         }
         //Connected to the server or floor application
         using (StreamWriter sw = new StreamWriter(pipeClient))
         {
             sw.Write(optionVal);
         }
     }
 }
Beispiel #19
0
    private void client()
    {
        System.IO.Pipes.NamedPipeClientStream pipeClient = new System.IO.Pipes.NamedPipeClientStream(".", "testpipe", System.IO.Pipes.PipeDirection.InOut, System.IO.Pipes.PipeOptions.None);

        if (pipeClient.IsConnected != true)
        {
            pipeClient.Connect();
        }

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

        string temp;

        temp = sr.ReadLine();

        if (temp == "Waiting")
        {
            try
            {
                sw.WriteLine("Test Message");
                sw.Flush();
                pipeClient.Close();
            }
            catch (Exception ex) { throw ex; }
        }
    }
Beispiel #20
0
    public string getMessage()
    {
        NamedPipeClientStream pipe_client =
            new NamedPipeClientStream(".", pipe_name, PipeDirection.InOut);

        try
        {
            Console.WriteLine("connect");
            pipe_client.Connect();
            Console.WriteLine("connect--e");
        }
        catch (InvalidOperationException e)
        {
            Console.WriteLine("InvalidOperationException" + e);
        }
        StreamReader sr = new StreamReader(pipe_client);

        string message;
        while ((message = sr.ReadLine()) != null)
        {
            Console.WriteLine(message);
        }

        return "hoge";
    }
Beispiel #21
0
        private static void SendCommand(string sContent)
        {

            string sProgramName = ConfigurationManager.AppSettings["dstProgramName"];
            using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", sProgramName,
                                                                           PipeDirection.Out,
                                                                        PipeOptions.None))
            {
                
                Console.WriteLine("Attempting to connect to pipe...");
                try
                {
                    pipeClient.Connect(1000);
                }
                catch
                {
                    Console.WriteLine("The Pipe server must be started in order to send data to it.");
                    return;
                }
                Console.WriteLine("Connected to pipe.");

                using (StreamWriter sw = new StreamWriter(pipeClient))
                {
                    sw.Write(sContent);
                }
            }
        }
 public bool TryConnectToNamedPipeWithSpinWait(int timeoutMs, CancellationToken cancellationToken)
 {
     using (var pipeStream = new NamedPipeClientStream(".", _pipeName, PipeDirection.InOut, PipeOptions.Asynchronous))
     {
         return BuildServerConnection.TryConnectToNamedPipeWithSpinWait(pipeStream, timeoutMs, cancellationToken);
     }
 }
Beispiel #23
0
		static void Main()
		{
			ClearModifierKeys();

			var args = Environment.GetCommandLineArgs();
			var multi = args.Any(arg => arg == "-multi");

			if ((multi) || (mutex.WaitOne(TimeSpan.Zero, true)))
			{
				var app = new App();
				if (!multi)
					SetupPipeWait(app);
				app.Run();
				if (!multi)
					mutex.ReleaseMutex();
				return;
			}

			// Server already exists; connect and send command line
			var pipeClient = new NamedPipeClientStream(".", IPCName, PipeDirection.InOut);
			pipeClient.Connect();
			var buf = Coder.StringToBytes(string.Join(" ", args.Skip(1).Select(arg => $"\"{arg.Replace(@"""", @"""""")}\"")), Coder.CodePage.UTF8);
			var size = BitConverter.GetBytes(buf.Length);
			pipeClient.Write(size, 0, size.Length);
			pipeClient.Write(buf, 0, buf.Length);
		}
        private static void PipesWriter(string pipeName)
        {
            try
            {
                using (var pipeWriter = new NamedPipeClientStream("TheRocks", pipeName, PipeDirection.Out))
                {
                    pipeWriter.Connect();
                    WriteLine("writer connected");

                    bool completed = false;
                    while (!completed)
                    {
                        string input = ReadLine();
                        if (input == "bye") completed = true;

                        byte[] buffer = Encoding.UTF8.GetBytes(input);
                        pipeWriter.Write(buffer, 0, buffer.Length);
                    }
                }
                WriteLine("completed writing");
            }
            catch (Exception ex)
            {
                WriteLine(ex.Message);
            }
        }
        public static Task<bool> SendMessageToServer(string pipeName, string message)
        {
            return Task.Run(() =>
            {
                try
                {
                    using (var pipe = new NamedPipeClientStream(".", pipeName, PipeDirection.Out))
                    {
                        pipe.Connect(1000);

                        using (var stream = new StreamWriter(pipe))
                        {
                            stream.Write(message);
                            stream.Flush();
                        }
                    }

                    return true;
                }
                catch (TimeoutException)
                {
                }
                catch (Exception exc)
                {
                    Log.Debug(string.Format("Sending message on: {0}", pipeName), exc);
                }

                return false;
            });
        }
Beispiel #26
0
        public DxDeviceCtrl()
        {
            KeybdPipeSwCollection=new Collection<StreamWriter>();

            var id = 0;
            bool failed = false;
            for (id = 0; false == failed; ++id)
            {
                var KeybdPipe = new NamedPipeClientStream(".", "DxKeybdPipe" + id.ToString(), PipeDirection.Out);
                try
                {
                    KeybdPipe.Connect(50);
                    if (true == KeybdPipe.IsConnected)
                    {
                        var KeybdPipeSW = new StreamWriter(KeybdPipe);
                        KeybdPipeSW.AutoFlush = true;
                        KeybdPipeSwCollection.Add(KeybdPipeSW);
                    }
                    else
                    {
                        failed = true;
                    }
                }
                catch (Exception )
                {
                    failed = true;
                }
            }
        }
Beispiel #27
0
        static void Main()
        {
            using (Mutex mutex = new Mutex(false, @"Global\simpledlnaguilock")) {
            #if !DEBUG
            if (!mutex.WaitOne(0, false)) {
              using (var pipe = new NamedPipeClientStream(".", "simpledlnagui", PipeDirection.Out)) {
            try {
              pipe.Connect(10000);
              pipe.WriteByte(1);
            }
            catch (Exception) {
            }
            return;
              }
            }
            GC.Collect();
            #endif

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            using (var main = new FormMain()) {
              try {
            Application.Run(main);
              }
              catch (Exception ex) {
            log4net.LogManager.GetLogger(typeof(Program)).Fatal("Encountered fatal unhandled exception", ex);
            throw;
              }
            }
              }
        }
 public static void SendMessage(String optionVal)
 {
     using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "RipplePipe", PipeDirection.Out, PipeOptions.Asynchronous))
     {
         try
         {
             pipeClient.Connect(2000);
         }
         catch (Exception)
         {
             //Try once more
             try
             {
                 pipeClient.Connect(5000);
             }
             catch (Exception)
             {
                 return;
             }
         }
         //Connected to the server or floor application
         using (StreamWriter sw = new StreamWriter(pipeClient))
         {
             sw.Write(optionVal);
         }
     }
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="NamedPipeCommunicationChannel" /> class.
        /// </summary>
        /// <param name="endPoint">The end point.</param>
        /// <param name="pipeStream">An existing pipe stream or <c>null</c> to create client.</param>
        public NamedPipeCommunicationChannel(NamedPipeEndPoint endPoint, PipeStream pipeStream = null)
        {
            _endPoint = endPoint;

            if (pipeStream != null) _pipeStream = pipeStream;
            else
            {
                var client = new NamedPipeClientStream(".", endPoint.Name, PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.WriteThrough);

                // connect overload with timeout is extremely processor intensive
                int elapsed = 0, connectionTimeout = endPoint.ConnectionTimeout * 1000;

            CONNECT:
                try
                {
                    client.Connect(0);
                }
                catch (TimeoutException)
                {
                    Thread.Sleep(CONNECT_ATTEMPT_INTERVAL_MS);

                    if (endPoint.ConnectionTimeout != Timeout.Infinite && (elapsed += CONNECT_ATTEMPT_INTERVAL_MS) > connectionTimeout)
                        throw new TimeoutException("The host failed to connect. Timeout occurred.");

                    goto CONNECT;
                }

                _pipeStream = client;
            }

            _buffer = new byte[ReceiveBufferSize];
            _syncLock = new object();
        }
Beispiel #30
0
        static int Main(string[] args)
        {
            if (args.Length != 1)
            {
                return 1;
            }

            var pipeName = args[0];

            //Console.WriteLine(nameof(pipeName) + " = " + pipeName);

            using (var pipeClient = new NamedPipeClientStream(pipeName))
            {
                pipeClient.Connect();

                // Receive meta data first.
                var messageTypeCommunicator = new CodeShardCommunicator<Type>(pipeClient);
                var messageType = messageTypeCommunicator.Receive();
                var entryPointCommunicator = new CodeShardCommunicator<object>(pipeClient);
                var entryPointInstance = entryPointCommunicator.Receive();

                // Get run method for the hosted user code.
                var entryPointType = entryPointInstance.GetType();
                var expectedInterfaceType = typeof(ICodeShardEntryPoint<>).MakeGenericType(messageType);
                var runMethodInfo = expectedInterfaceType.GetMethods()[0];

                // Create communicator instance for the hosted user code.
                var communicatorType = typeof(CodeShardCommunicator<>).MakeGenericType(messageType);
                var communicatorInstance = Activator.CreateInstance(communicatorType, pipeClient);

                runMethodInfo.Invoke(entryPointInstance, new object[] { communicatorInstance });
            }

            return 0;
        }
Beispiel #31
0
        public void ThreadStartClient(object obj)
        {
            // Ensure that we only start the client after the server has created the pipe
            ManualResetEvent SyncClientServer = (ManualResetEvent)obj;

            // Only continue after the server was created -- otherwise we just fail badly
            // SyncClientServer.WaitOne();

            using (NamedPipeClientStream pipeStream = new NamedPipeClientStream(pipeName))
            {
                // The connect function will indefinately wait for the pipe to become available
                // If that is not acceptable specify a maximum waiting time (in ms)
                pipeStream.Connect(5000);

                //Console.WriteLine("[Client] Pipe connection established");
                using (StreamWriter sw = new StreamWriter(pipeStream))
                {
                    ////sw.AutoFlush = true;
                    if (Environment.GetCommandLineArgs().Length >= 2)
                    {
                        string fname = Environment.GetCommandLineArgs()[1];
                        sw.WriteLine(fname);
                        sw.Flush();
                    }
                }
            }
        }       
Beispiel #32
0
        /// <summary>
        /// After registering at least ApplicationStarts, call this method to ensure this instance is the single instance.
        /// If this instance is the first (single) instance, the ApplicationStarts event will be triggered.
        /// If this instance is not the first (single) instance, the application will be terminated immediately.
        /// </summary>
        public void RunSingleInstance()
        {
            // get information from the mutex if we're the first/single instance.
            bool owned = false;

            mutex = new Mutex(false, "Global\\{" + id.ToString() + "}", out owned);
            if (owned) // we "own" the mutex, meaning we're the first instance
            {
                // inform the application to begin startup
                if (ApplicationStarts != null)
                {
                    ApplicationStarts(this, new EventArgs());
                }

                // prepare a named pipe to receive data from subsequent start attempts
                ListenNamedPipe();
            }
            else // In this case, we're a subsequent instance.
            {
                // Connect to the named pipe, if able, to signal the original instance that subsequent startup has been attempted
                // This could be extended to send actual data to the original instance
                try
                {
                    var np = new System.IO.Pipes.NamedPipeClientStream(".", id.ToString(), PipeDirection.Out);
                    np.Connect(0);
                    np.Dispose();
                }
                catch { }

                // Regardless, shut down immediately
                Application.Current.Shutdown();
            }
        }
Beispiel #33
0
 // .ctor with existing handle
 public UnixNamedPipeClient(NamedPipeClientStream owner, SafePipeHandle safePipeHandle)
 {
     this.owner  = owner;
     this.handle = safePipeHandle;
     // FIXME: dunno how is_async could be filled.
 }