• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# Pipes.NamedPipeClientStream类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.IO.Pipes.NamedPipeClientStream的典型用法代码示例。如果您正苦于以下问题:C# NamedPipeClientStream类的具体用法?C# NamedPipeClientStream怎么用?C# NamedPipeClientStream使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



NamedPipeClientStream类属于System.IO.Pipes命名空间,在下文中一共展示了NamedPipeClientStream类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: InvokeFunc

        /// <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;
                }
            }
        }
开发者ID:Rambalac,项目名称:ProcessThreads,代码行数:66,代码来源:ProcessThreadExecutor.cs


示例2: Main

 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);
         }
     }
 }
开发者ID:chenbk85,项目名称:UnityShaderCompiler,代码行数:27,代码来源:Program.cs


示例3: StartListening

        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);
        }
开发者ID:jeffgriffin,项目名称:ChromiumBackground,代码行数:34,代码来源:PipeHandler.cs


示例4: Main

        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();
        }
开发者ID:fxmozart,项目名称:MetaTraderBridge,代码行数:31,代码来源:PipeClient.cs


示例5: CheckUnenrolledHostShouldRemoved

        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();
        }
开发者ID:robhoes,项目名称:xenadmin,代码行数:32,代码来源:RequestUploadTaskTests.cs


示例6: Connect

        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();
                }
            }
        }
开发者ID:webbers,项目名称:dongle.net,代码行数:33,代码来源:PipeClient.cs


示例7: SendCommandToCore

 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;
 }
开发者ID:xantilas,项目名称:videobrowser,代码行数:29,代码来源:MBClientConnector.cs


示例8: Run

        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;
                }
            }
        }
开发者ID:peteraritchie,项目名称:Rock.Messaging,代码行数:29,代码来源:NamedPipeQueueProducer.cs


示例9: evaluate

 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?");
     }
 }
开发者ID:randomdude,项目名称:Lavalamp,代码行数:31,代码来源:ruleItem-winamp-base.cs


示例10: readMessage

 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;
 }
开发者ID:jonwingfield,项目名称:AutoTest.Net,代码行数:33,代码来源:PipeClient.cs


示例11: Sockets

 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();
     }
 }
开发者ID:appsec-labs,项目名称:Advanced_Packet_Editor,代码行数:25,代码来源:Sockets.cs


示例12: SendMessage

        /// <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);
                    }
                }
            }
        }
开发者ID:bestpetrovich,项目名称:devicehive-.net,代码行数:32,代码来源:NamedPipeMessageBus.cs


示例13: backgroundWorker1_DoWork

        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);
                }
            }
        }
开发者ID:geckosoft,项目名称:OpenRA,代码行数:25,代码来源:InstallPackagesDialog.cs


示例14: Close

        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));
        }
开发者ID:alexyats,项目名称:DecklinkStreamer,代码行数:34,代码来源:PipeServer.cs


示例15: Start

        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;
        }
开发者ID:irtnog,项目名称:PipeToCom,代码行数:27,代码来源:Connection.cs


示例16: SendCommand

        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);
                }
            }
        }
开发者ID:zhoukongjava,项目名称:Biobanking,代码行数:27,代码来源:Program.cs


示例17: getMessage

    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";
    }
开发者ID:otama-jaccy,项目名称:Pipe,代码行数:25,代码来源:PipeClient.cs


示例18: Main

		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);
		}
开发者ID:xyandro,项目名称:NeoEdit,代码行数:26,代码来源:InstanceManager.cs


示例19: TryConnectToNamedPipeWithSpinWait

 public bool TryConnectToNamedPipeWithSpinWait(int timeoutMs, CancellationToken cancellationToken)
 {
     using (var pipeStream = new NamedPipeClientStream(".", _pipeName, PipeDirection.InOut, PipeOptions.Asynchronous))
     {
         return BuildServerConnection.TryConnectToNamedPipeWithSpinWait(pipeStream, timeoutMs, cancellationToken);
     }
 }
开发者ID:XieShuquan,项目名称:roslyn,代码行数:7,代码来源:DesktopBuildClientTests.cs


示例20: SendMessageToServer

        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;
            });
        }
开发者ID:gertadam,项目名称:MRobot.Windows,代码行数:30,代码来源:NamedPipeChannel.cs



注:本文中的System.IO.Pipes.NamedPipeClientStream类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Pipes.NamedPipeServerStream类代码示例发布时间:2022-05-26
下一篇:
C# Packaging.PackagePart类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap