C# 如何从管道发送和接收数据
我有一个WinC窗体应用程序 我还有一个c DLL DLL以32位格式编译。 GUI使用64位格式编译 我正在使用管道在两种不同的编译之间简化messagubng DLL客户端向我的GUI服务器发送一个字节数组映像 这是我的服务器代码:C# 如何从管道发送和接收数据,c#,named-pipes,C#,Named Pipes,我有一个WinC窗体应用程序 我还有一个c DLL DLL以32位格式编译。 GUI使用64位格式编译 我正在使用管道在两种不同的编译之间简化messagubng DLL客户端向我的GUI服务器发送一个字节数组映像 这是我的服务器代码: public partial class Form1 : Form { public delegate void NewMessageDelegate(System.Drawing.Bitmap NewMessage);
public partial class Form1 : Form
{
public delegate void NewMessageDelegate(System.Drawing.Bitmap NewMessage);
private PipeServer pipeName;
public Form1()
{
InitializeComponent();
pipeName = new PipeServer();
pipeName.PipeMessage += new DelegateMessage(PipesMessageHandler);
}
private void cmdListen_Click(object sender, EventArgs e)
{
try
{
pipeName.Listen("TestPipe");
txtMessage.Text = "Listening - OK";
cmdListen.Enabled = false;
}
catch (Exception)
{
txtMessage.Text = "Error Listening";
}
}
private void PipesMessageHandler(System.Drawing.Bitmap message)
{
try
{
if (this.InvokeRequired)
{
pictureBox1.Invoke((MethodInvoker)(() => pictureBox1.Image = message));
}
else
{
pictureBox1.Image = message;
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
}
因此,用户将按下我的“cmdListen”按钮
这是我在DLL中的客户端代码:
class PipeClient
{
public void Send(Bitmap frame, string PipeName, int TimeOut = 1000)
{
try
{
NamedPipeClientStream pipeStream = new NamedPipeClientStream(".", PipeName, PipeDirection.Out, PipeOptions.Asynchronous);
pipeStream.Connect(TimeOut);
Debug.WriteLine("[Client] Pipe connection established");
byte[] _buffer = null;
using (var ms = new MemoryStream())
{
frame.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
_buffer = ms.ToArray();
}
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);
}
}
}
“发送”由我的DLL中的计时器调用,以将图像“泵送”到我的GUI应用程序
这一切都有效
我需要添加/做的是在触发计时器之前将一些参数从serverGUI传递到我的DLLclient
因此,在我的客户端DLL中,我将有以下函数
public void InitDLL(object[] args)
{
//do something with these parameters
//start timer off
}
那么,如何使用管道从GUI调用此函数呢
我注意到管道方向可以设置为InOut。但是我不确定如何简单地向我的服务器应用程序添加一些代码,以便向我的客户端发送消息。是的,如果您想在两个方向上使用相同的管道,请将管道设置为双向。您从服务器发送数据的方式与客户端发送数据的方式相同:获取流,然后写入流。请注意,一些基于管道的实现使用两个不同的管道,每个方向一个。那也行。