上一次提到,我们的WCF程序宿主是发布到IIS上面的。虽然这样做未尝不可,不过不便于我们进行“开始”或“停止”WCF服务的操作。所以再次尝试了编写以窗体应用程序作为WCF服务宿主的方式,并取得了成功。而下文则记录整个程序的建立过程。
一、创建WCF服务
首先创建一个WCF服务项目,项目名称为WCFService,解决方案为WCFDemo。
新建的WCF服务项目已经包含了一个GetData()函数,我们这个例子中直接使用这个函数。
二、创建WCF宿主
同样地,我们为这个解决方案增加一个WCF服务宿主项目。项目名称为WCFServerHost,程序类型为Windows窗体应用程序。
在程序的窗口上放置一个按钮,并将按钮的标题改为“开启服务”,修改后的窗口如下:
然后为程序添加System.ServiceModel和WcfService两个引用
最后,双击程序按钮添加如下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | private?ServiceHost Host = null; private?void?button1_Click(object?sender, EventArgs e) { ????if?(Host == null) ????{ ????????Host = new?ServiceHost(typeof(WCFService.Service1)); ? ????????//绑定 ????????System.ServiceModel.Channels.Binding httpBinding = new?BasicHttpBinding(); ????????//终结点 ????????Host.AddServiceEndpoint(typeof(WCFService.IService1), httpBinding, "http://localhost:8002/"); ????????if?(Host.Description.Behaviors.Find<System.ServiceModel.Description.ServiceMetadataBehavior>() == null) ????????{ ????????????//行为 ????????????ServiceMetadataBehavior behavior = new?ServiceMetadataBehavior(); ????????????behavior.HttpGetEnabled = true; ? ????????????//元数据地址 ????????????behavior.HttpGetUrl = new?Uri("http://localhost:8002/Service1"); ????????????Host.Description.Behaviors.Add(behavior); ????????????? ????????????//启动 ????????????Host.Open(); ????????} ????} } |
---|
然后,在关闭窗口事件中添加如下代码:
1 2 3 4 5 6 7 | private?void?Form1_FormClosed(object?sender, FormClosedEventArgs e) { ????if?(Host != null) ????{ ????????Host.Close(); ????} } |
---|
好了,现在运行应用程序,开启服务后,在IE浏览器中输入http://localhost:8002/Service1,检查是否正常显示元数据。
三、编写客户端程序
在解决方案中再添加一个新的Windows窗体应用程序,程序名称为WCFClient。
然后,在关闭窗口事件中添加如下代码:在程序项目上按右键,选择“添加服务引用……”。在添加服务引用对话框的地址栏位中,输入:http://localhost:8002/Service1,发现服务后,将服务命名空间改为ServiceReferenceDemo,然后点击“确定”按钮。
添加完服务后,我们在程序窗口上放置一个按钮,并将按钮标题命名为“执行”。双击“执行”按钮,并编写如下代码:
1 2 3 4 5 6 7 8 9 | private?void?button1_Click(object?sender, EventArgs e) { ????using?(ServiceReferenceDemo.Service1Client sc = new?ServiceReferenceDemo.Service1Client()) ????{ ????????sc.Open(); ????????MessageBox.Show(sc.GetData(10)); ????????sc.Close(); ????} } |
---|
四、测试执行
首先确保Host程序已经运行、然后执行客户端程序,并点击“执行”按钮,检查是否有一个正确的返回值。