Skip to main content
 首页 » 编程设计

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

2024年02月13日15落叶无声

在我的应用程序中,我使用匿名管道发送包含 int 和枚举(技术上也是 int)和字符串的消息。我的管道完全按照此 MSDN 中的管道进行设置和建模文章。我不想让它尽可能简单,更重要的是尽可能快。我不想做的是将消息的前 32 位设为 int,接下来的 32 位设为枚举,剩下的都是消息。我怎样才能做到这一点?

我最初只是想将字符串格式化为一定长度,如 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 静态方法正在执行一些带有定界符的自定义序列化,这是我想要摆脱的。

请您参考如下方法:

您可以使用 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(); 
}