using Calculator.Service;
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.Windows.Forms;
namespace Calculator.Host
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
ServiceHost host = null;
private void btnOpen_Click(object sender, EventArgs e)
{
host = new ServiceHost(typeof(CalculatorService));
host.AddServiceEndpoint(typeof(ICalculator), new WSHttpBinding(), "http://www.easck.com//localhost:8008/Calculator/metadata");
host.Description.Behaviors.Add(behavior);
}
host.Opened += delegate { label1.Text = "服务已经启动!"; };
host.Open();
}
private void btnClose_Click(object sender, EventArgs e)
{
if (host.State != CommunicationState.Closed)
{
host.Closed += delegate { label1.Text = "服务已经停止!"; };
host.Close();
}
}
}
}

五、创建客户端调用服务
服务被成功寄宿后,服务端便开始了服务调用请求的监听工作。此外,服务寄宿将服务描述通过元数据的形式发布出来,相应的客户端就可以获取这些元数据,创建爱你客户端程序进行服务的消费。在VS下,当我们添加服务引用的时候,VS在内部帮我们实现元数据的获取,并借组这些元数据通过代码生成工具自动生成用于服务调用的服务代理相关代码和相应的配置。

我们可以创建CalculatorClient对象,执行相应方法调用服务操作。
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;
namespace Calculator.Client
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.Text = "+";
}
private void button1_Click(object sender, EventArgs e)
{
CalculatorService.CalculatorClient client = new CalculatorService.CalculatorClient();
double x = Convert.ToDouble (textBox1.Text);
double y = Convert.ToDouble(textBox2.Text);
double result=0;
string operater = comboBox1.Text;
switch (operater )
{
case "+":
result = client.Add(x, y);
break;
case "-":
result = client.Subtract(x, y);
break;
case "*":
result = client.Multiply(x, y);
break;
case "/":
if (y==0)
{
MessageBox.Show("除数不能为0!");
return;
}
result = client.Divide(x, y);
break;
}
label1.Text = textBox1.Text + comboBox1.Text + textBox2.Text + " = " + Convert.ToString(result);
}
}
}










