wcf服务端
1,新建一个“windows窗体程序”名称为WCFServer2。
2,然后添加一个“WCF服务”名称为Service1。具体步骤为:解决方案试图中,选中“WCFServer2”项目,右键,在弹出菜单中选择“添加->新建项”。
3,双击主窗体,在它的Load事件中编写代码启动wcf服务:BasicHttpBinding方式启动wcf服务。此文件代码如下:
using System.ServiceModel; using System.ServiceModel.Description; //… ServiceHost m_ServiceHost; //… private void Form1_Load(object sender, EventArgse) { //NetTcpBinding方式启动wcf服务 m_ServiceHost = new ServiceHost(typeof(Service1));//Service1是wcf服务的类名称 NetTcpBindingbinding = new NetTcpBinding(); UribaseAddress = new Uri(string.Format("net.tcp://localhost:10086/WCFHostServer/Service1")); m_ServiceHost.AddServiceEndpoint(typeof(IService1),binding, baseAddress); m_ServiceHost.Open(); }
4,在 IService1.cs中增加一个方法Init,同时增加ISvrToCliCallBack接口.
namespace WCFServer2 { // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的接口名“IService1”。 [ServiceContract(CallbackContract= typeof(ISvrToCliCallBack))] public interface IService1 { [OperationContract] voidDoWork(); [OperationContract] voidInit(); } public interface ISvrToCliCallBack { [OperationContract(IsOneWay= true)] voidNotifyClientMsg(string devStateInfo); } }
5, 在Service1.cs中实现接口的方法Init初始化。
public static ISvrToCliCallBack userCallBack; //... public void Init() { userCallBack = OperationContext.Current.GetCallbackChannel<ISvrToCliCallBack>(); }
6,主窗口增加按钮。
private voidbutton1_Click(object sender, EventArgs e) { Service1.userCallBack.NotifyClientMsg("服务端给客户端通知啦"); }
7,修改app.config,WCFServer2.Service1的binding由"wsHttpBinding"改成"wsDualHttpBinding"
客服端
1,新建一个“windows窗体程序”名称为WCFClient2。
2,增加服务引用。服务引用地址到服务端的app.config查看,就是baseAddress。
3.在FormClient中继承接口IService1Callback,实现方法NotifyClientMsg
4,主窗口启动是初始化。
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using WCFClient2.ServiceReference1; using System.ServiceModel; namespace WCFClient2 { public partial class Form1 : Form, IService1Callback { publicForm1() { InitializeComponent(); } public void NotifyClientMsg(stringdevStateInfo) { MessageBox.Show(devStateInfo,"ddd"); } IService1m_Innerclient; privatevoid Form1_Load(objectsender, EventArgs e) { InstanceContextm_CallBackContext; m_CallBackContext = new InstanceContext(this); DuplexChannelFactory<IService1> m_ChannelFactory; NetTcpBindingbinding = new NetTcpBinding(); stringstrUrl = string.Format("net.tcp://{0}:{1}/WCFHostServer/Service1", "localhost",10085); UribaseAddress = new Uri(strUrl); m_ChannelFactory = new DuplexChannelFactory<IService1>(m_CallBackContext, binding, new EndpointAddress(baseAddress)); m_Innerclient =m_ChannelFactory.CreateChannel(); Service1Clienthost = new ServiceReference1.Service1Client(m_CallBackContext); host.Init();//调用GetSvrTime获取到wcf服务器上的时间 } } }