使用对象C#的异步命名管道

时间:2019-03-26 17:52:29

标签: c#

我正在尝试学习使用命名管道进行通信。以下代码项目在显示原始字符串示例方面做得很好。

https://www.codeproject.com/Tips/492231/Csharp-Async-Named-Pipes

我正在努力将原始字符串的发送更改为发送对象。

有人可以演示如何发送订单而不是字符串吗?

我有一些代码可以发送一个对象,但是在将代码项目与这个想法结合在一起时遇到了问题。

这是我的pipeClient

  public class Order
    {
        public string ProductName { get; set; }
        public int Quantity { get; set; }
        public string CustomerName { get; set; }
        public string Address { get; set; }
    }


    class PipeClient
    {
        public void Send(string SendStr, string PipeName, int TimeOut = 1000)
        {
            try
            {
                NamedPipeClientStream pipeStream = new NamedPipeClientStream(".", "orders", PipeDirection.Out, PipeOptions.Asynchronous);

                // The connect function will indefinitely wait for the pipe to become available
                // If that is not acceptable specify a maximum waiting time (in ms)
                Order order = new Order()
                {
                    Address = SendStr,
                    CustomerName = "John",
                    ProductName = "Visual Studio 2015",
                    Quantity = 1
                };
                string serialised = Json.Net.JsonNet.Serialize(order);

                pipeStream.Connect(TimeOut);
                Debug.WriteLine("[Client] Pipe connection established");

                byte[] _buffer = Encoding.UTF8.GetBytes(serialised);
                pipeStream.BeginWrite(_buffer, 0, _buffer.Length, AsyncSend, pipeStream);
            }
            catch (TimeoutException oEX)
            {
                Debug.WriteLine(oEX.Message);
            }
        }

        private void AsyncSend(IAsyncResult iar)
        {
            try
            {
                // Get the pipe
                NamedPipeClientStream pipeStream = (NamedPipeClientStream)iar.AsyncState;

                // End the write
                pipeStream.EndWrite(iar);
                pipeStream.Flush();
                pipeStream.Close();
                pipeStream.Dispose();
            }
            catch (Exception oEX)
            {
                Debug.WriteLine(oEX.Message);
            }
        }
    }

我的代码在这里中断-> pipeStream.Connect(TimeOut);

这是我的服务器编辑

 private void WaitForConnectionCallBack(IAsyncResult iar)
        {
            try
            {
                // Get the pipe
                NamedPipeServerStream pipeServer = (NamedPipeServerStream)iar.AsyncState;
                // End waiting for the connection
                pipeServer.EndWaitForConnection(iar);

               StringBuilder messageBuilder = new StringBuilder();
               string messageChunk = string.Empty;
               byte[] buffer = new byte[255];

                do
                {
                    pipeServer.Read(buffer, 0, buffer.Length);
                    messageChunk = Encoding.UTF8.GetString(buffer);
                    messageBuilder.Append(messageChunk);
                    buffer = new byte[buffer.Length];
                }
                while (!pipeServer.IsMessageComplete);
                //Order order = Json.Net.JsonNet.Deserialize<Order>(messageBuilder.ToString());
                PipeMessage.Invoke(messageBuilder.ToString());

                // Read the incoming message
                //pipeServer.Read(buffer, 0, 255);

                // Convert byte buffer to string
                //string stringData = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
                //Debug.WriteLine(stringData + Environment.NewLine);

                // Pass message back to calling form
                //PipeMessage.Invoke(stringData);

                // Kill original sever and create new wait server
                pipeServer.Close();
                pipeServer = null;
                pipeServer = new NamedPipeServerStream(_pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);

                // Recursively wait for the connection again and again....
                pipeServer.BeginWaitForConnection(new AsyncCallback(WaitForConnectionCallBack), pipeServer);
            }
            catch
            {
                return;
            }
        }
.
.
. Server Form 


   private void PipesMessageHandler(string message)
        {
            try
            {
                if (this.InvokeRequired)
                {
                    this.Invoke(new NewMessageDelegate(PipesMessageHandler), message);
                }
                else
                {
                    Order order = Json.Net.JsonNet.Deserialize<Order>(message);
                    txtOutput.Text = txtOutput.Text +
                                     Environment.NewLine + 
                                     String.Format("Address: {0}" +
                                                   "Customer: {1}" +
                                                   "Product: {2}" +
                                                   "Quantity: {3}", order.Address, order.CustomerName, order.ProductName, order.Quantity.ToString());
                    //txtMessage.Text = message;
                }
            }
            catch (Exception ex)
            {

                Debug.WriteLine(ex.Message);
            }

        }

0 个答案:

没有答案