1.新建两个WinForm, Server, Client
2.Server中添加引用System.ServiceModel
3.定义一个接口,其中包含一个TestMethod方法,也就是服务协定。服务协定就是附加了ServiceContract特性的接口,方法附加OperationContractAttribute特性,作为服务操作,可以供客户端程序调用,如果不加OperationContractAttribute特性,就不向客户端公开该方法。
[ServiceContract]
public interface IService
{
[OperationContract]
string TestMethod();
}
4.创建MyService类实现IService接口
class MyService : IService
{
public string TestMethod()
{
return "Hello World";
}
}
5.在Server界面添加按钮和文本框
在两个按钮中添加
ServiceHost host;
private void startService_Click(object sender, EventArgs e)
{
// 基址URI,必须,HTTP方案
Uri baseURI = new Uri("http://localhost:8008/Service");
host = new ServiceHost(typeof(MyService), baseURI);
// 向服务器添终结点
WSHttpBinding binding = new WSHttpBinding();
// 这里不需要安全验证
binding.Security.Mode = SecurityMode.None;
host.AddServiceEndpoint(typeof(IService), binding, "my");
// 为了能让VS生成客户端代码,即WSDL文档,故要添加以下行为
ServiceMetadataBehavior mdBehavior = new ServiceMetadataBehavior()
{
HttpGetEnabled = true
};
host.Description.Behaviors.Add(mdBehavior);
//如果服务顺利启动,则提示,处理Opened事件
host.Opened += (sender2, e2) => { textBox1.AppendText("服务已启动\r\n"); };
// 启动服务器
try
{
host.Open();
}
catch (Exception ex)
{
textBox1.AppendText(ex.Message);
}
}
private void closeService_Click(object sender, EventArgs e)
{
// 关闭服务器
host.Close();
textBox1.AppendText("服务已关闭\r\n");
}
6.以管理员身份启动Service
7.保持服务开启,在Client中添加服务引用
8.在Client界面中添加按钮和文本框
在按钮中添加
WS.ServiceClient client = new WS.ServiceClient();
string msg = client.TestMethod();
textBox1.AppendText(msg + "\r\n");
9.运行Client
参考自 http://blog.csdn.net/tcjiaan/article/details/7792726
推荐原作者的传说中的WCF系列
这就是个学习实践笔记