{ //服務契約
[ServiceContract]
public interface Interface1
{ //操作契約
[OperationContract]
string Hello();
}
}
class HelloClass:ClassLibrary1.Interface1
{
public string Hello()
{
return "Hello wcf!";
}
}
基本創建一個服務。創建之后需要部署。一般分為配置文件部署和代碼部署。
A:Address 意味着在哪里(也含有傳輸方式信息)
B:Binding 意味着怎么做(與地址的傳輸方式要匹配)
C:Contract意味着做什么(服務契約)
<system.ServiceModel>
<services>
<service>
<endpoint/> /*服務和終結點*/
</service>
</services>
<bindings> /*綁定(可選)*/
<binding>
</binding>
</bindings>
<behaviors> /*行為(可選) */
<behavior>
</behavior>
</behaviors>
</system.ServiceModel>
“http://www.sina.com.cn:3200/mathservice”這個URI 具有以下四個部分:
– 方案:http:
– 計算機:www.sina.com.cn
– (可選)端口:3200
– 路徑:/mathservice
<services>
<service name="ConsoleApplication1.HelloClass" behaviorConfiguration="testBehavior"> <!--name為實現該契約的類-->
<host>
<baseAddresses>
<add baseAddress=" http://localhost:8002/test"></add><!--基地址-->
</baseAddresses>
</host>
<endpoint address="" binding="basicHttpBinding" contract="ClassLibrary1.Interface1"></endpoint>
<!--已有baseAddress基地址,address可為空;binding為綁定類型,對應Http協議;contract為所公開的協議,即所創建的服務契約接口-->
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="testBehavior"> <!--與上面behaviorConfiguration="testBehavior"保持一致,可為空-->
<serviceMetadata httpGetEnabled="true"/> <!--指定是否要發布元數據以HTTP/Get獲取-->
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
ServiceHost host = null;
host = new ServiceHost(typeof(ConsoleApplication1.HelloClass));
host.Open();
Console.WriteLine("服務已經啟動!");
Console.ReadLine();
host = new ServiceHost(typeof(ConsoleApplication2.HelloClass));
NetTcpBinding tcpBind = new NetTcpBinding();//設定綁定類型
string address = "net.tcp://localhost:3200/hello";
host.AddServiceEndpoint(typeof(ClassLibrary1.Interface1), tcpBind, address);//在服務終結點添加,協議,綁定類型,終結點地址
host.Opened += delegate { Console.WriteLine("服務已啟動!"); Console.ReadLine(); };
host.Open();
//綁定形式
NetTcpBinding bind = new NetTcpBinding();
//提供客服端與服務建立連接的地址
EndpointAddress address = new EndpointAddress("net.tcp://localhost:3200/hello");
//客戶端通關通道工廠將消息發送到不同配置的服務終結點
ChannelFactory<ClassLibrary1.Interface1> factory = new ChannelFactory<ClassLibrary1.Interface1>(bind, address);
//通過通道工廠對象來獲取指定類型
ClassLibrary1.Interface1 myobject = factory.CreateChannel();
string s = myobject.Hello();
Console.WriteLine(s);
Console.ReadLine();
先啟動服務,在運行客戶端。