子曾经曰过

  博客园  :: 首页  ::  ::  ::  :: 管理

新建一个工程,新建一个类库StartService,新建一个类CodeWCF.cs,代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Runtime.Remoting;
using System.Runtime;
using System.ServiceModel.Description;
using System.Runtime.Serialization;

namespace StartService
{
public class CodeWCF
{
static void Main()
{
ServiceHost host
= new ServiceHost(typeof(Service), new Uri("http://localhost:8001")); //实例化一个宿主

try
{
//定义一个服务元数据行为对象
ServiceMetadataBehavior smb = host.Description.Behaviors.Find<ServiceMetadataBehavior>();
if (smb == null) //如果这个对象是空,意思就是没有这个服务元数据行为
smb = new ServiceMetadataBehavior(); //实例化一个服务元数据行为
smb.HttpGetEnabled = true; //让客户端能得到元数据
smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15; //元数据导出规则WS1.5
host.Description.Behaviors.Add(smb); //在宿主上加上定义的服务元数据行为
//在宿主上加上定义的元数据节点如同下句作用
//<endpoint name="endpointmex" address="mex1" binding="mexHttpBinding" contract="IMetadataExchange" />
host.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName, MetadataExchangeBindings.CreateMexHttpBinding(), "mex");
//定义客户端终结点
System.ServiceModel.Channels.Binding wsbinding = new WSHttpBinding();
//加上终结点
host.AddServiceEndpoint(typeof(IService), wsbinding, "");

host.Open();
Console.WriteLine(
"服务已启动...");
Console.ReadLine();
}
catch
{
CommunicationException ce
= new CommunicationException();
Console.WriteLine(ce.Message);
Console.ReadLine();
}
}

}

[ServiceContract]
public interface IService
{
[OperationContract]
void Fun();
}
public class Service : IService
{
public void Fun()
{ Console.WriteLine(
"hello world!"); }
}
}

第二种代码写法:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Runtime.Remoting;
using System.Runtime;
using System.ServiceModel.Description;
using System.Runtime.Serialization;
using System.ServiceModel.Channels;

namespace StartService
{
class CodeWCF2
{
static void Main()
{
ServiceHost host
= new ServiceHost(typeof(Service), new Uri("http://localhost:90"));
//需要命名空间 using System.ServiceModel.Channels;
BindingElement bindingElement = new HttpTransportBindingElement();
CustomBinding binding
= new CustomBinding(bindingElement);

ServiceMetadataBehavior smb
= host.Description.Behaviors.Find<ServiceMetadataBehavior>();
if (smb == null)
{
smb
= new ServiceMetadataBehavior();
host.Description.Behaviors.Add(smb);
}
host.AddServiceEndpoint(
typeof(IMetadataExchange), binding, "mex");
host.AddServiceEndpoint(
typeof(IService), new WSHttpBinding(), "");
host.Open();
Console.WriteLine(
"服务已经启动...");
Console.ReadLine();

}
}

[ServiceContract]
public interface IService
{
[OperationContract]
void Fun();
}
public class Service : IService
{
public void Fun()
{ Console.WriteLine(
"hello world!"); }
}
}
posted on 2011-02-22 22:28  人的本质是什么?  阅读(312)  评论(0编辑  收藏  举报