WCF實(shí)現(xiàn)進(jìn)程間管道通信Demo分享
一、代碼結(jié)構(gòu):
二、數(shù)據(jù)實(shí)體類:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace DataStruct
{
 /// <summary>
 /// 測試數(shù)據(jù)實(shí)體類
 /// </summary>
 [DataContract]
 public class TestData
 {
  [DataMember]
  public double X { get; set; }
  [DataMember]
  public double Y { get; set; }
 }
}
三、服務(wù)端服務(wù)接口和實(shí)現(xiàn):
接口:
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using DataStruct;
namespace WCFServer
{
 /// <summary>
 /// 服務(wù)接口
 /// </summary>
 [ServiceContract]
 public interface IClientServer
 {
  /// <summary>
  /// 計(jì)算(測試方法)
  /// </summary>
  [OperationContract]
  double Calculate(TestData data);
 }
}
實(shí)現(xiàn):
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using DataStruct;
namespace WCFServer
{
 /// <summary>
 /// 服務(wù)實(shí)現(xiàn)
 /// </summary>
 [ServiceBehavior()]
 public class ClientServer : IClientServer
 {
  /// <summary>
  /// 計(jì)算(測試方法)
  /// </summary>
  public double Calculate(TestData data)
  {
   return Math.Pow(data.X, data.Y);
  }
 }
}
四、服務(wù)端啟動服務(wù):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Utils;
using WCFServer;
namespace 服務(wù)端
{
 public partial class Form1 : Form
 {
  public Form1()
  {
   InitializeComponent();
  }
  private void Form1_Load(object sender, EventArgs e)
  {
   BackWork.Run(() =>
   {
    OpenClientServer();
   }, null, (ex) =>
   {
    MessageBox.Show(ex.Message);
   });
  }
  /// <summary>
  /// 啟動服務(wù)
  /// </summary>
  private void OpenClientServer()
  {
   NetNamedPipeBinding wsHttp = new NetNamedPipeBinding();
   wsHttp.MaxBufferPoolSize = 524288;
   wsHttp.MaxReceivedMessageSize = 2147483647;
   wsHttp.ReaderQuotas.MaxArrayLength = 6553600;
   wsHttp.ReaderQuotas.MaxStringContentLength = 2147483647;
   wsHttp.ReaderQuotas.MaxBytesPerRead = 6553600;
   wsHttp.ReaderQuotas.MaxDepth = 6553600;
   wsHttp.ReaderQuotas.MaxNameTableCharCount = 6553600;
   wsHttp.CloseTimeout = new TimeSpan(0, 1, 0);
   wsHttp.OpenTimeout = new TimeSpan(0, 1, 0);
   wsHttp.ReceiveTimeout = new TimeSpan(0, 10, 0);
   wsHttp.SendTimeout = new TimeSpan(0, 10, 0);
   wsHttp.Security.Mode = NetNamedPipeSecurityMode.None;
   Uri baseAddress = new Uri("net.pipe://localhost/pipeName1");
   ServiceHost host = new ServiceHost(typeof(ClientServer), baseAddress);
   ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
   host.Description.Behaviors.Add(smb);
   ServiceBehaviorAttribute sba = host.Description.Behaviors.Find<ServiceBehaviorAttribute>();
   sba.MaxItemsInObjectGraph = 2147483647;
   host.AddServiceEndpoint(typeof(IClientServer), wsHttp, "");
   host.Open();
  }
 }
}
五、客戶端數(shù)據(jù)實(shí)體類和服務(wù)接口類與服務(wù)端相同
六、客戶端服務(wù)實(shí)現(xiàn):
using DataStruct;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Text;
using System.Threading.Tasks;
using WCFServer;
namespace DataService
{
 /// <summary>
 /// 服務(wù)實(shí)現(xiàn)
 /// </summary>
 public class ClientServer : IClientServer
 {
  ChannelFactory<IClientServer> channelFactory;
  IClientServer proxy;
  public ClientServer()
  {
   CreateChannel();
  }
  /// <summary>
  /// 創(chuàng)建連接客戶終端WCF服務(wù)的通道
  /// </summary>
  public void CreateChannel()
  {
   string url = "net.pipe://localhost/pipeName1";
   NetNamedPipeBinding wsHttp = new NetNamedPipeBinding();
   wsHttp.MaxBufferPoolSize = 524288;
   wsHttp.MaxReceivedMessageSize = 2147483647;
   wsHttp.ReaderQuotas.MaxArrayLength = 6553600;
   wsHttp.ReaderQuotas.MaxStringContentLength = 2147483647;
   wsHttp.ReaderQuotas.MaxBytesPerRead = 6553600;
   wsHttp.ReaderQuotas.MaxDepth = 6553600;
   wsHttp.ReaderQuotas.MaxNameTableCharCount = 6553600;
   wsHttp.SendTimeout = new TimeSpan(0, 10, 0);
   wsHttp.Security.Mode = NetNamedPipeSecurityMode.None;
   channelFactory = new ChannelFactory<IClientServer>(wsHttp, url);
   foreach (OperationDescription op in channelFactory.Endpoint.Contract.Operations)
   {
    DataContractSerializerOperationBehavior dataContractBehavior = op.Behaviors.Find<DataContractSerializerOperationBehavior>() as DataContractSerializerOperationBehavior;
    if (dataContractBehavior != null)
    {
     dataContractBehavior.MaxItemsInObjectGraph = 2147483647;
    }
   }
  }
  /// <summary>
  /// 計(jì)算(測試方法)
  /// </summary>
  public double Calculate(TestData data)
  {
   proxy = channelFactory.CreateChannel();
   try
   {
    return proxy.Calculate(data);
   }
   catch (Exception ex)
   {
    throw ex;
   }
   finally
   {
    (proxy as ICommunicationObject).Close();
   }
  }
 }
}
七、客戶端調(diào)用服務(wù)接口:
using DataService;
using DataStruct;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Utils;
using WCFServer;
namespace 客戶端
{
 public partial class Form1 : Form
 {
  public Form1()
  {
   InitializeComponent();
  }
  //測試1
  private void button1_Click(object sender, EventArgs e)
  {
   button1.Enabled = false;
   txtSum.Text = string.Empty;
   IClientServer client = new ClientServer();
   double num1;
   double num2;
   double sum = 0;
   if (double.TryParse(txtNum1.Text, out num1) && double.TryParse(txtNum2.Text, out num2))
   {
    DateTime dt = DateTime.Now;
    BackWork.Run(() =>
    {
     sum = client.Calculate(new TestData(num1, num2));
    }, () =>
    {
     double time = DateTime.Now.Subtract(dt).TotalSeconds;
     txtTime.Text = time.ToString();
     txtSum.Text = sum.ToString();
     button1.Enabled = true;
    }, (ex) =>
    {
     button1.Enabled = true;
     MessageBox.Show(ex.Message);
    });
   }
   else
   {
    button1.Enabled = true;
    MessageBox.Show("請輸入合法的數(shù)據(jù)");
   }
  }
  //測試2
  private void button2_Click(object sender, EventArgs e)
  {
   button2.Enabled = false;
   txtSum.Text = string.Empty;
   IClientServer client = new ClientServer();
   double num1;
   double num2;
   double sum = 0;
   if (double.TryParse(txtNum1.Text, out num1) && double.TryParse(txtNum2.Text, out num2))
   {
    DateTime dt = DateTime.Now;
    BackWork.Run(() =>
    {
     for (int i = 0; i < 1000; i++)
     {
      sum = client.Calculate(new TestData(num1, num2));
     }
    }, () =>
    {
     double time = DateTime.Now.Subtract(dt).TotalSeconds;
     txtTime.Text = time.ToString();
     txtSum.Text = sum.ToString();
     button2.Enabled = true;
    }, (ex) =>
    {
     button2.Enabled = true;
     MessageBox.Show(ex.Message);
    });
   }
   else
   {
    button2.Enabled = true;
    MessageBox.Show("請輸入合法的數(shù)據(jù)");
   }
  }
 }
}
八、工具類BackWork類:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
/**
 * 使用方法:
BackWork.Run(() => //DoWork
{
}, () => //RunWorkerCompleted
{
}, (ex) => //錯誤處理
{
});
 
*/
namespace Utils
{
 /// <summary>
 /// BackgroundWorker封裝
 /// 用于簡化代碼
 /// </summary>
 public class BackWork
 {
  /// <summary>
  /// 執(zhí)行
  /// </summary>
  /// <param name="doWork">DoWork</param>
  /// <param name="workCompleted">RunWorkerCompleted</param>
  /// <param name="errorAction">錯誤處理</param>
  public static void Run(Action doWork, Action workCompleted, Action<Exception> errorAction)
  {
   bool isDoWorkError = false;
   Exception doWorkException = null;
   BackgroundWorker worker = new BackgroundWorker();
   worker.DoWork += (s, e) =>
   {
    try
    {
     doWork();
    }
    catch (Exception ex)
    {
     isDoWorkError = true;
     doWorkException = ex;
    }
   };
   worker.RunWorkerCompleted += (s, e) =>
   {
    if (!isDoWorkError)
    {
     try
     {
      if (workCompleted != null) workCompleted();
     }
     catch (Exception ex)
     {
      errorAction(ex);
     }
    }
    else
    {
     errorAction(doWorkException);
    }
   };
   worker.RunWorkerAsync();
  }
 }
}
九、效果圖示:
以上這篇WCF實(shí)現(xiàn)進(jìn)程間管道通信Demo分享就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持我們。
欄 目:C#教程
下一篇:實(shí)例分享C#中Explicit和Implicit用法
本文標(biāo)題:WCF實(shí)現(xiàn)進(jìn)程間管道通信Demo分享
本文地址:http://www.jygsgssxh.com/a1/C_jiaocheng/5327.html
您可能感興趣的文章
- 01-10C#實(shí)現(xiàn)txt定位指定行完整實(shí)例
 - 01-10WinForm實(shí)現(xiàn)仿視頻播放器左下角滾動新聞效果的方法
 - 01-10C#實(shí)現(xiàn)清空回收站的方法
 - 01-10C#實(shí)現(xiàn)讀取注冊表監(jiān)控當(dāng)前操作系統(tǒng)已安裝軟件變化的方法
 - 01-10C#實(shí)現(xiàn)多線程下載文件的方法
 - 01-10C#實(shí)現(xiàn)Winform中打開網(wǎng)頁頁面的方法
 - 01-10C#實(shí)現(xiàn)遠(yuǎn)程關(guān)閉計(jì)算機(jī)或重啟計(jì)算機(jī)的方法
 - 01-10C#自定義簽名章實(shí)現(xiàn)方法
 - 01-10C#文件斷點(diǎn)續(xù)傳實(shí)現(xiàn)方法
 - 01-10winform實(shí)現(xiàn)創(chuàng)建最前端窗體的方法
 


閱讀排行
本欄相關(guān)
- 01-10C#通過反射獲取當(dāng)前工程中所有窗體并
 - 01-10關(guān)于ASP網(wǎng)頁無法打開的解決方案
 - 01-10WinForm限制窗體不能移到屏幕外的方法
 - 01-10WinForm繪制圓角的方法
 - 01-10C#實(shí)現(xiàn)txt定位指定行完整實(shí)例
 - 01-10WinForm實(shí)現(xiàn)仿視頻播放器左下角滾動新
 - 01-10C#停止線程的方法
 - 01-10C#實(shí)現(xiàn)清空回收站的方法
 - 01-10C#通過重寫Panel改變邊框顏色與寬度的
 - 01-10C#實(shí)現(xiàn)讀取注冊表監(jiān)控當(dāng)前操作系統(tǒng)已
 
隨機(jī)閱讀
- 04-02jquery與jsp,用jquery
 - 01-10delphi制作wav文件的方法
 - 01-11ajax實(shí)現(xiàn)頁面的局部加載
 - 08-05織夢dedecms什么時候用欄目交叉功能?
 - 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
 - 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置
 - 01-10C#中split用法實(shí)例總結(jié)
 - 08-05dedecms(織夢)副欄目數(shù)量限制代碼修改
 - 01-10使用C語言求解撲克牌的順子及n個骰子
 - 08-05DEDE織夢data目錄下的sessions文件夾有什
 


