共享内存方式应该最简单易用的
直接上代码,下面列出了2种,一种是映射视图,一种是映射流,任选一种即可
服务端:
MemoryMappedFile memoryAccessor = MemoryMappedFile.CreateNew("ProcessCommunicationAccessor", 500, MemoryMappedFileAccess.ReadWrite);//创建共享内存映射文件对象,第一个参数为映射的名称,与客户端需要对应,500为大小,单位为字节,MemoryMappedFileAccess为访问权限,是读写还是只读 只写,此处不能使用Using 否则脱离Using 就会释放,客户端无法获取到此名称的内存映射对象
using (var accessor = memoryAccessor.CreateViewAccessor())//获取映射文件对象的视图
{
var helo = Encoding.UTF8.GetBytes("Accessor");
accessor.WriteArray(0, helo, 0, helo.Length);//将给定的值写入此视图中
richTextBox1.Text += Environment.NewLine + "Accessor Send Val:Accessor";
}
MemoryMappedFile memoryStream = MemoryMappedFile.CreateNew("ProcessCommunicationStream", 500, MemoryMappedFileAccess.ReadWrite);//创建流的映射文件对象
using (var stream = memoryStream.CreateViewStream())//获取映射文件的流
{
var helo = Encoding.UTF8.GetBytes("Stream");
stream.Write(helo, 0, helo.Length);//将给定的值写入此内存流中
richTextBox1.Text += Environment.NewLine + "Accessor Send Val:Stream";
}
客户端:
对应上面也是有2种接收方式
MemoryMappedFile memoryAccessor = MemoryMappedFile.OpenExisting("ProcessCommunicationAccessor");//获取服务端定义的ProcessCommunicationAccessor名称的内存映射文件然后调用ReadArray方法读取到服务端写入的数据
using (var accessor = memoryAccessor.CreateViewAccessor())
{
var s = new byte[999];
var read = accessor.ReadArray(0, s, 0, s.Length);
var str = Encoding.UTF8.GetString(s);
richTextBox1.Text += Environment.NewLine + "Accessor Read Val:" + str.ToString();
}
MemoryMappedFile memoryStream = MemoryMappedFile.OpenExisting("ProcessCommunicationStream");//获取服务端定义的ProcessCommunicationStream名称的内存映射文件然后调用ReadToEnd方法读取到服务端写入的数据
using (var stream = memoryStream.CreateViewStream())
{
using (var reader = new StreamReader(stream))
{
var str = reader.ReadToEnd();
richTextBox1.Text += Environment.NewLine + "Stream Read Val:" + str + "\r\n";
}
}