如何使用固定的32位长度通过匿名管道发送整数?

时间:2013-12-13 18:05:35

标签: c# optimization serialization named-pipes

在我的应用程序中,我使用Anonymous Pipe发送包含int,enum(技术上也是int)和字符串的消息。我的管道正好在这篇MSDN文章中的管道之后进行设置和建模。我不想保持这个简单,更重要的是尽可能快。我不想做的是使消息的前32位为int,接下来的32位是enum,并且所有内容都是消息。我怎么能做到这一点?

我最初只是将字符串格式化为特定长度,如this答案,但格式实际上会产生不同长度的字符串,如果数字为负数与正数。这似乎是错误的方法,我觉得我需要这些整数的二进制表示,而不是字符串表示。

目前我发送的信息如下:

m_RemoteLogger = new Process();
m_RemoteLogger.StartInfo.FileName = @"C:\Work\Library\Utilities.Logging.exe";

m_LoggingStream = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable);

// Pass the client process a handle to the server.
m_RemoteLogger.StartInfo.Arguments = m_LoggingStream.GetClientHandleAsString() + " \"" + m_Name + "\" \"" + m_Source + "\" " + m_Size;
m_RemoteLogger.StartInfo.UseShellExecute = false;
m_RemoteLogger.Start();

m_LoggingStream.DisposeLocalCopyOfClientHandle();

m_LoggingStreamWriter = new StreamWriter(m_LoggingStream);
m_LoggingStreamWriter.AutoFlush = true;
// Send a 'sync message' and wait for client to receive it.
m_LoggingStreamWriter.WriteLine("SYNC");

m_LoggingStream.WaitForPipeDrain();

并接受他们:

if (args.Length > 0) {
    m_EventLog = CreateEventLog(args[1], args[2], int.Parse(args[3]));

    using (PipeStream pipeClient =
        new AnonymousPipeClientStream(PipeDirection.In, args[0])) {

        using (StreamReader sr = new StreamReader(pipeClient)) {
            string temp;

            // Wait for startup information from our creator. 
            do {
                temp = sr.ReadLine();
            }
            while (!temp.StartsWith("SYNC"));

            // Read messages to log from the stream and write to the event log
            while ((temp = sr.ReadLine()) != null) {
                var loggingInformation = LogMessageFormatter.ConvertFromString(temp);
                m_EventLog.WriteEntry(loggingInformation.Item1, loggingInformation.Item2,
                    loggingInformation.Item3);

            }
        }
    }
}

LogMessageFormatter静态方法正在使用分隔符执行一些自定义序列化,我想要远离它。

2 个答案:

答案 0 :(得分:2)

如果您想以二进制方式读取/写入 - 请使用BinaryReaderBinaryWriter而不是基于文本的StremReader / StreamWriter

using (BinaryWriter sw = new StreamWriter(pipeServer))
{ 
     sw.Write((int)1234);
     sw.Write((int)someEnumValue);
     sw.Write("my text");
}

答案 1 :(得分:2)

您可以使用BinaryWriter将二进制数据直接写入流。

using (AnonymousPipeServerStream pipeServer =
        new AnonymousPipeServerStream(PipeDirection.Out,
        HandleInheritability.Inheritable))
    {
       // .......
       int id = 123456;
       string msg = "hello";
       using(var binWriter = new BinaryWriter(pipeServer))
       {
          binWriter.Write(id);
          binWriter.Write(msg);
       }
    }
}

在管道的另一侧,使用BinaryReader

using (var rdr = new BinaryReader(pipeClient))
{
   int id = rdr.ReadInt32();
   string msg = rdr.ReadString();
}