参考文章: 点击打开链接
虽然是转载, 也有自己的加工——步骤更清晰,代码也都是自己亲自运行过的。 如要原味请点上面链接。
1. 创建控制台程序,添加一个 Service1.cs, 再添加一个下图的引用。
2. Service1.cs
using System.ServiceModel;
namespace WCFStudy1
{
[ServiceContract]
public interface IService1
{
[OperationContract]
string SendMessage(string clientInput);
}
public class Service1 : IService1
{
#region IService1 Members
public string SendMessage(string clientInput)
{
return string.Format("Server Get Message: {0}", clientInput);
}
#endregion
}
}
3. Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace WCFStudy1
{
class Program
{
static void Main(string[] args)
{
// 创建一个独立AppDomain作为服务端。
AppDomain.CreateDomain("Server1").DoCallBack(delegate
{
ServiceHost host = new ServiceHost(typeof(Service1));
host.AddServiceEndpoint(typeof(IService1), //契约(C)
new BasicHttpBinding(), //绑定(B)
"http://localhost:9999/myservice"); //地址(A)
host.Open();
});
// 下面是客户端
ChannelFactory<IService1> factory = new ChannelFactory<IService1>(
new BasicHttpBinding(),
"http://localhost:9999/myservice");
IService1 client = factory.CreateChannel();
var reply = client.SendMessage("Hello WCF");
Console.WriteLine(reply);
Console.Read();
}
}
}
结果: