WCF入门讲解

article/2025/10/5 14:14:18

一、简单WCF服务TCP和HTTP传输协议

二、实例管理

1、实例管理-单调服务

介绍:单调服务的一个实例创建于每个方法调用之前,调用完成后会立即销毁该服务实例。

2、实例管理-会话

介绍:一个配置了私有会话的服务通常无法支持多达几十个(或者上百个)独立的客户端,只因为创建专门的服务实例的代价太大。

3、实例管理-单例服务

介绍:一种极端的共享服务,单例服务会在创建宿主时创建,且它的生命周期是无限的,只有在关闭宿主时,单例服务才会被释放。

4、实例管理-限流

介绍:并发会话数,默认值为处理器计数(或内核)的100倍;并发调用最大数,默认值为 处理器计数(或内核 )的16倍;并发实例的最大数量,默认等于最大并发调用的数目和最大并发会话数目(单个处理器116个会话)的和

三、操作

1、回调操作

介绍:客户端调用接口完成后,服务端通过回调方式调用客户端方法

四、事务

1、事务-ConcurrentMode.Single

介绍:一次只允许一个调用者进入,如果同时有多个并发调用,那么调用请求会进入一个队列里等待服务处理。

2、事务-ConcurrentMode.Multiple

介绍:不会为服务实例提供同步访问机制,不会队列化客户端请求,而是在消息到达时就立即发送出去。
附: 非同步访问事务

3、事务-ConcurrentMode.Reentrant

介绍:是对concurrentMode.Single模式的改进。

五、队列服务

1、简单使用

2、最终客户端Web.config文件

新建项目:WCFDemo

引入命名空间:
using System.ServiceModel;
using System.Runtime.Serialization;

添加接口:IUserContract(服务契约)

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
namespace WCFDemo
{
    [ServiceContract]
    public interface IUserContract
    {
        [OperationContract]
        bool Login(string userName, string pwd);
    }
}

添加类:UserContract 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WCFDemo
{
    public class UserContract : IUserContract
    {
        public bool Login(string userName, string pwd)
        {
            if (userName == "x" && pwd == "x")
            {
                return true;
            }
            return false;
        }
    }
}

添加类:UserInfo(数据契约)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Runtime.Serialization;
namespace WCFDemo
{
    [DataContract]
    public class UserInfo
    {
        [DataMember]
        public string UserName { get; set; }
[DataMember]
        public string Pwd { get; set; }
    }
}

Program类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Channels;

namespace WCFDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            ServiceHost host = new ServiceHost(typeof(UserContract));
ServiceMetadataBehavior metadataBehavior;
metadataBehavior = host.Description.Behaviors.Find<ServiceMetadataBehavior>();
var httpUri = new Uri("http://192.168.1.104:8002/WCFDemo/UserContract");
var tcpUri = new Uri("net.tcp://192.168.1.104:8001/WCFDemo/UserContract");
if (metadataBehavior == null)
            {
                metadataBehavior = new ServiceMetadataBehavior();
                metadataBehavior.HttpGetEnabled = true;
                metadataBehavior.HttpGetUrl = httpUri;
                host.Description.Behaviors.Add(metadataBehavior);
}

            NetTcpBinding tcpBinding = new NetTcpBinding();
WSHttpBinding wsBinding = new WSHttpBinding();
//以管理员方式运行CMD输入:netsh http add urlacl url=http://+:8002/WCFDemo/UserContract/ user=Everyone
            host.AddServiceEndpoint(typeof(IUserContract), wsBinding, httpUri);
tcpBinding.MaxBufferPoolSize = 52428800;
            tcpBinding.MaxBufferSize = 6553600;
            tcpBinding.MaxReceivedMessageSize = 6553600;
            tcpBinding.PortSharingEnabled = false;
            tcpBinding.Security.Mode = SecurityMode.None;//取消身份验证
host.AddServiceEndpoint(typeof(IUserContract), tcpBinding, tcpUri);
host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "net.tcp://192.168.1.104:8001/service/");//TCPBindding时,一定要有
host.Open();
Console.WriteLine("服务已启用");
Console.ReadKey();
        }
    }
}

新建MVCWeb项目:WCFWeb

添加服务引用: net.tcp://192.168.1.104:8001/service/【注意】
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WCFWeb.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
public ActionResult Index()
        {
            ServiceReference1.UserContractClient client = new ServiceReference1.UserContractClient("NetTcpBinding_IUserContract");
            bool b = client.Login("x", "x");
return View();
        }
}
}

web.config文件:

<system.serviceModel>
    <bindings>
      <netTcpBinding>
        <binding name="NetTcpBinding_IUserContract">
          <security mode="None" />
        </binding>
      </netTcpBinding>
      <wsHttpBinding>
        <binding name="WSHttpBinding_IUserContract" />
      </wsHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://192.168.1.104:8002/WCFDemo/UserContract"
        binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IUserContract"
        contract="ServiceReference1.IUserContract" name="WSHttpBinding_IUserContract">
        <identity>
          <userPrincipalName value="AdministratorPC\john" />
        </identity>
      </endpoint>
      <endpoint address="net.tcp://192.168.1.104:8001/WCFDemo/UserContract"
        binding="netTcpBinding" bindingConfiguration="NetTcpBinding_IUserContract"
        contract="ServiceReference1.IUserContract" name="NetTcpBinding_IUserContract" />
    </client>
  </system.serviceModel>

使用WCFclient测试:

VS2012自带WcfTestClient.exe测试工具,文件位置:C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE



 

单调服务

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
namespace WCFDemo
{
    [ServiceContract]
    public interface IMonotoneContract
    {
        [OperationContract]
         int Add();
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WCFDemo
{
 //配置为单调
     [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class MonotoneContract : IMonotoneContract, IDisposable
    {
        private int count = 0;
       
        public int Add()
        {
            count++;
            return count;
        }

        public void Dispose()
        {
            
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Channels;

namespace WCFDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            ServiceHost host = new ServiceHost(typeof(MonotoneContract));
ServiceMetadataBehavior metadataBehavior;
metadataBehavior = host.Description.Behaviors.Find<ServiceMetadataBehavior>();
var httpUri = new Uri("http://192.168.1.104:8002/WCFDemo/MonotoneContract");
var tcpUri = new Uri("net.tcp://192.168.1.104:8001/WCFDemo/MonotoneContract");
if (metadataBehavior == null)
            {
                metadataBehavior = new ServiceMetadataBehavior();
                metadataBehavior.HttpGetEnabled = true;
                metadataBehavior.HttpGetUrl = httpUri;
                host.Description.Behaviors.Add(metadataBehavior);
}

            NetTcpBinding tcpBinding = new NetTcpBinding();
WSHttpBinding wsBinding = new WSHttpBinding();
//以管理员方式运行CMD输入:netsh http add urlacl url=http://+:8002/WCFDemo/MonotoneContract/ user=Everyone
            host.AddServiceEndpoint(typeof(IMonotoneContract), wsBinding, httpUri);
tcpBinding.MaxBufferPoolSize = 52428800;
            tcpBinding.MaxBufferSize = 6553600;
            tcpBinding.MaxReceivedMessageSize = 6553600;
            tcpBinding.PortSharingEnabled = false;
            tcpBinding.Security.Mode = SecurityMode.None;//取消身份验证
host.AddServiceEndpoint(typeof(IMonotoneContract), tcpBinding, tcpUri);
host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "net.tcp://192.168.1.104:8001/service/");//TCPBindding时,一定要有
host.Open();
Console.WriteLine("服务已启用");
Console.ReadKey();
        }
    }
}
未配置单调服务测试:点击11次,显示效果如下
配置为单调服务: 点击11次,显示效果如下



 

操作-会话

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
namespace WCFDemo
{
     [ServiceContract(SessionMode=SessionMode.Required)]
    public interface IMonotoneContract
    {
        [OperationContract]
         int Add();
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
namespace WCFDemo
{
   
     [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
    public class MonotoneContract : IMonotoneContract, IDisposable
    {
private int count = 0;
public int Add()
        {
            count++;
            return count;
        }

        public void Dispose()
        {
}
    }
}
主程序Program同上
配置为会话: 点击11次,显示效果如下



操作-单例服务

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
namespace WCFDemo
{
     [ServiceContract(SessionMode=SessionMode.Required)]
    public interface IMonotoneContract
    {
        [OperationContract]
         int Add();
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
namespace WCFDemo
{
    
     [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    public class MonotoneContract : IMonotoneContract, IDisposable
    {
private int count = 0;
public int Add()
        {
            count++;
            return count;
        }

        public void Dispose()
        {
}
    }
}
配置为会话:打开两个WCFTestClient,分别点击Invoke一次 ,显示效果如下



实例管理-限流

添加类:ServiceThrottleHelper
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
namespace WCFDemo
{
    public static class ServiceThrottleHelper
    {
        public static void SetThrottle(this ServiceHost host, int maxCalls, int maxSessions, int maxInstances)
        {
            ServiceThrottlingBehavior serviceThrottle = new ServiceThrottlingBehavior();
            serviceThrottle.MaxConcurrentCalls = maxCalls;
            serviceThrottle.MaxConcurrentSessions = maxSessions;
            serviceThrottle.MaxConcurrentInstances = maxInstances;
            host.SetThrottle(serviceThrottle);
        }
public static void SetThrottle(this ServiceHost host, ServiceThrottlingBehavior serviceThrottle, bool overrideConfig)
        {
            if (host.State == CommunicationState.Opened)
            {
                throw new InvalidOperationException("Host is already opended");
            }
            ServiceThrottlingBehavior throttle = host.Description.Behaviors.Find<ServiceThrottlingBehavior>();
            if (throttle == null)
            {
                host.Description.Behaviors.Add(serviceThrottle);
                return;
            }
            if (overrideConfig == false)
            {
                return;
            }
            host.Description.Behaviors.Remove(throttle);
            host.Description.Behaviors.Add(serviceThrottle);
        }
public static void SetThrottle(this ServiceHost host, ServiceThrottlingBehavior serviceThrottle)
        {
            host.SetThrottle(serviceThrottle, false);
        }
    }
}
主程序:Program
host.SetThrottle(12, 34, 56);//限流(最大并发调用、最大并发会话数、最大并发实例)

操作-回调操作

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
namespace WCFDemo
{
    interface IMonotoneContractCallback
    {
         [OperationContract]
        void OnCallback();
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
namespace WCFDemo
{
     [ServiceContract(CallbackContract = typeof(IMonotoneContractCallback))]
    public interface IMonotoneContract
    {
        [OperationContract]
        int Add();
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
namespace WCFDemo
{
    //ConcurrencyMode = ConcurrencyMode.Reentrant 配置重入已支持回调
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Reentrant)]
    public class MonotoneContract : IMonotoneContract
    {
        static List<IMonotoneContractCallback> m_Callbacks = new List<IMonotoneContractCallback>();
private int count = 0;
public int Add()
        {
            count++;
/*
            IMonotoneContractCallback callbacks = OperationContext.Current.GetCallbackChannel<IMonotoneContractCallback>();
            if (m_Callbacks.Contains(callbacks) == false)
            {
                m_Callbacks.Add(callbacks);
            }
            CallClients();
            */
            OperationContext.Current.GetCallbackChannel<IMonotoneContractCallback>().OnCallback();
return count;
        }
public static void CallClients()
        {
            Action<IMonotoneContractCallback> invoke = callback => callback.OnCallback();
m_Callbacks.ForEach(invoke);
}

       
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Channels;

namespace WCFDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            ServiceHost host = new ServiceHost(typeof(MonotoneContract));
ServiceMetadataBehavior metadataBehavior;
metadataBehavior = host.Description.Behaviors.Find<ServiceMetadataBehavior>();
var httpUri = new Uri("http://192.168.1.104:8002/WCFDemo/MonotoneContract");
var tcpUri = new Uri("net.tcp://192.168.1.104:8001/WCFDemo/MonotoneContract");
if (metadataBehavior == null)
            {
                metadataBehavior = new ServiceMetadataBehavior();
                metadataBehavior.HttpGetEnabled = true;
                metadataBehavior.HttpGetUrl = httpUri;
                host.Description.Behaviors.Add(metadataBehavior);
}

            NetTcpBinding tcpBinding = new NetTcpBinding();
WSHttpBinding wsBinding = new WSHttpBinding();
//以管理员方式运行CMD输入:netsh http add urlacl url=http://+:8002/WCFDemo/MonotoneContract/ user=Everyone
            //host.AddServiceEndpoint(typeof(IMonotoneContract), wsBinding, httpUri);(不支付回调)
tcpBinding.MaxBufferPoolSize = 52428800;
            tcpBinding.MaxBufferSize = 6553600;
            tcpBinding.MaxReceivedMessageSize = 6553600;
            tcpBinding.PortSharingEnabled = false;
            tcpBinding.Security.Mode = SecurityMode.None;//取消身份验证
host.AddServiceEndpoint(typeof(IMonotoneContract), tcpBinding, tcpUri);
host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "net.tcp://192.168.1.104:8001/service/");//TCPBindding时,一定要有
host.SetThrottle(12, 34, 56);//限流
host.Open();
Console.WriteLine("服务已启用");
Console.ReadKey();
        }
    }
}
客户端:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WCFWeb.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
public ActionResult Index()
        {
             MonotoneContractCallback monotoneContractCallback = new  MonotoneContractCallback();
            System.ServiceModel.InstanceContext context = new System.ServiceModel.InstanceContext(monotoneContractCallback);
ServiceReference1.MonotoneContractClient client = new ServiceReference1.MonotoneContractClient(context, "NetTcpBinding_IMonotoneContract");
            var b = client.Add();
return View();
        }
}
class  MonotoneContractCallback :  WCFWeb.ServiceReference1.IMonotoneContractCallback
    {
        public void OnCallback()
        {
            string a = "b";
        }
    }
}
运行效果:





事务-Transactions

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
namespace WCFDemo
{
    [ServiceContract]
    public interface IMonotoneContract
    {
        [OperationContract]
         [TransactionFlow(TransactionFlowOption.Allowed)]
        int Add();
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Transactions;
using System.Data;
using System.Data.SqlClient;
namespace WCFDemo
{
    [Serializable]
     [ServiceBehavior(ReleaseServiceInstanceOnTransactionComplete = false, InstanceContextMode = InstanceContextMode.PerSession)]
    public class MonotoneContract : IMonotoneContract
    {
        private int count = 0;
 [OperationBehavior(TransactionAutoComplete = true, TransactionScopeRequired = true)]
        public int Add()
        {
            count++;
using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection("Data Source=.;Initial Catalog=test2;Integrated Security=True"))
            {
                if (con.State != ConnectionState.Open)
                {
                    con.Open();
                }
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandText = "insert into Table_1 values('" + Guid.NewGuid() + "','" + count + "');";
                cmd.ExecuteNonQuery();
            }
return count;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Channels;

namespace WCFDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            ServiceHost host = new ServiceHost(typeof(MonotoneContract));
ServiceMetadataBehavior metadataBehavior;
metadataBehavior = host.Description.Behaviors.Find<ServiceMetadataBehavior>();
var httpUri = new Uri("http://192.168.1.104:8002/WCFDemo/MonotoneContract");
var tcpUri = new Uri("net.tcp://192.168.1.104:8001/WCFDemo/MonotoneContract");
if (metadataBehavior == null)
            {
                metadataBehavior = new ServiceMetadataBehavior();
                metadataBehavior.HttpGetEnabled = true;
                metadataBehavior.HttpGetUrl = httpUri;
                host.Description.Behaviors.Add(metadataBehavior);
}

            NetTcpBinding tcpBinding = new NetTcpBinding();
WSHttpBinding wsBinding = new WSHttpBinding();
//以管理员方式运行CMD输入:netsh http add urlacl url=http://+:8002/WCFDemo/MonotoneContract/ user=Everyone
            host.AddServiceEndpoint(typeof(IMonotoneContract), wsBinding, httpUri);//(不支付回调)
tcpBinding.MaxBufferPoolSize = 52428800;
            tcpBinding.MaxBufferSize = 6553600;
            tcpBinding.MaxReceivedMessageSize = 6553600;
            tcpBinding.PortSharingEnabled = false;
            tcpBinding.Security.Mode = SecurityMode.None;//取消身份验证
 tcpBinding.TransactionFlow = true;
            tcpBinding.TransactionProtocol = TransactionProtocol.WSAtomicTransactionOctober2004;
host.AddServiceEndpoint(typeof(IMonotoneContract), tcpBinding, tcpUri);
host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "net.tcp://192.168.1.104:8001/service/");//TCPBindding时,一定要有
host.Open();
Console.WriteLine("服务已启用");
Console.ReadKey();
        }
    }
}
客户端:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
namespace WCFWeb.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
public ActionResult Index()
        {

            ServiceReference1.MonotoneContractClient client = new ServiceReference1.MonotoneContractClient("NetTcpBinding_IMonotoneContract");
             using (TransactionScope scope = new TransactionScope())
            {
                var b = client.Add();
            }
            using (TransactionScope scope = new TransactionScope())
            {
                var b = client.Add();
            }
            using (TransactionScope scope = new TransactionScope())
            {
                var b = client.Add();
                scope.Complete();
            } 
            using (TransactionScope scope = new TransactionScope())
            {
                var b = client.Add();
                scope.Complete();
}
          
            return View();
        }
}

}
执行结果:(因为只提交了2次事务,因此只有2条记录)


 

服务并发模式-Single:   

[ServiceBehavior(ConcurrencyMode=ConcurrencyMode.Single)]
public class MonotoneContract : IMonotoneContract

服务并发模式-Multiple:

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
namespace WCFDemo
{
    [ServiceContract]
    public interface IMonotoneContract
    {
        [OperationContract]
        int Add();
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Transactions;
using System.Data;
using System.Data.SqlClient;
using System.Runtime.CompilerServices;
namespace WCFDemo
{
    [Serializable]
     [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)]
    public class MonotoneContract : IMonotoneContract
    {
        private int count = 0;
//锁住实例
         [MethodImpl(MethodImplOptions.Synchronized)]
        public int Add()
        {
            count++;
return count;
        }
    }
}
非同步访问与事务
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
namespace WCFDemo
{
    [ServiceContract]
    public interface IMonotoneContract
    {
        [OperationContract]
        int Add();
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Transactions;
using System.Data;
using System.Data.SqlClient;
using System.Runtime.CompilerServices;
namespace WCFDemo
{
    //事务性非同步服务必须明确将ReleaseServiceInstanceOnTransactionComplete设置为false
    [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, ReleaseServiceInstanceOnTransactionComplete = false)]
    public class MonotoneContract : IMonotoneContract
    {
        private int count = 0;
[OperationBehavior(TransactionScopeRequired = true)]
        public int Add()
        {
            count++;
           
            return count;
        }
    }
}

列列服务

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
namespace WCFDemo
{
    [ServiceContract]
    public interface IMonotoneContract
    {
        //使用消息队列,只能是单向的,不能有返回值
        [OperationContract(IsOneWay = true)]
        void Add();
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Transactions;
using System.Data;
using System.Data.SqlClient;
using System.Runtime.CompilerServices;
namespace WCFDemo
{
    public class MonotoneContract : IMonotoneContract
    {
        private int count = 0;
public void Add()
        {
            count++;
}
      
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Channels;
using System.Messaging;

namespace WCFDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            ServiceHost host = new ServiceHost(typeof(MonotoneContract));
ServiceMetadataBehavior metadataBehavior;
metadataBehavior = host.Description.Behaviors.Find<ServiceMetadataBehavior>();
var httpUri = new Uri("http://192.168.1.104:8002/WCFDemo/MonotoneContract");
var tcpUri = new Uri("net.tcp://192.168.1.104:8001/WCFDemo/MonotoneContract");
 var msqUri = new Uri("net.msmq://192.168.1.104/private/MyServiceQueue");
if (metadataBehavior == null)
            {
                metadataBehavior = new ServiceMetadataBehavior();
                metadataBehavior.HttpGetEnabled = true;
                metadataBehavior.HttpGetUrl = httpUri;
                host.Description.Behaviors.Add(metadataBehavior);
}
            NetMsmqBinding msqBinding = new NetMsmqBinding();
            if (MessageQueue.Exists(@".\private$\MyServiceQueue") == false)
            {
                MessageQueue.Create(@".\private$\MyServiceQueue", true);
            }
            msqBinding.Security.Mode =NetMsmqSecurityMode.None ;
NetTcpBinding tcpBinding = new NetTcpBinding();
WSHttpBinding wsBinding = new WSHttpBinding();
//以管理员方式运行CMD输入:netsh http add urlacl url=http://+:8002/WCFDemo/MonotoneContract/ user=Everyone
            host.AddServiceEndpoint(typeof(IMonotoneContract), wsBinding, httpUri);//(不支付回调)
tcpBinding.MaxBufferPoolSize = 52428800;
            tcpBinding.MaxBufferSize = 6553600;
            tcpBinding.MaxReceivedMessageSize = 6553600;
            tcpBinding.PortSharingEnabled = false;
            tcpBinding.Security.Mode = SecurityMode.None;//取消身份验证

             host.AddServiceEndpoint(typeof(IMonotoneContract), msqBinding, msqUri);
host.AddServiceEndpoint(typeof(IMonotoneContract), tcpBinding, tcpUri);
host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "net.tcp://192.168.1.104:8001/service/");//TCPBindding时,一定要有
host.Open();
Console.WriteLine("服务已启用");
Console.ReadKey();
        }
    }
}
客户端调用:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Messaging;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
namespace WCFWeb.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
public ActionResult Index()
        {

            ServiceReference1.MonotoneContractClient client = new ServiceReference1.MonotoneContractClient(" NetMsmqBinding_IMonotoneContract");
            if (MessageQueue.Exists(@".\private$\MyServiceQueue") == false)
            {
                MessageQueue.Create(@".\private$\MyServiceQueue", true);
            }
            client.Add();
return View();
        }
}

}

web.config:

<system.serviceModel>
    <bindings>
      <netMsmqBinding>
        <binding name="NetMsmqBinding_IMonotoneContract">
          <security mode="None" />
        </binding>
      </netMsmqBinding>
      <netTcpBinding>
        <binding name="NetTcpBinding_IMonotoneContract">
          <security mode="None" />
        </binding>
      </netTcpBinding>
      <wsHttpBinding>
        <binding name="WSHttpBinding_IMonotoneContract" />
      </wsHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://192.168.1.104:8002/WCFDemo/MonotoneContract"
        binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IMonotoneContract"
        contract="ServiceReference1.IMonotoneContract" name="WSHttpBinding_IMonotoneContract">
        <identity>
          <userPrincipalName value="AdministratorPC\john" />
        </identity>
      </endpoint>
      <endpoint address="net.msmq://192.168.1.104/private/MyServiceQueue"
        binding="netMsmqBinding" bindingConfiguration="NetMsmqBinding_IMonotoneContract"
        contract="ServiceReference1.IMonotoneContract" name="NetMsmqBinding_IMonotoneContract" />
      <endpoint address="net.tcp://192.168.1.104:8001/WCFDemo/MonotoneContract"
        binding="netTcpBinding" bindingConfiguration="NetTcpBinding_IMonotoneContract"
        contract="ServiceReference1.IMonotoneContract" name="NetTcpBinding_IMonotoneContract" />
    </client>
  </system.serviceModel>

http://chatgpt.dhexx.cn/article/orgIssdv.shtml

相关文章

关于WCF服务的使用(非常详细的步骤)

&#xff08;附上一篇对WCF基础讲解挺详细的一篇文章http://www.cnblogs.com/wayfarer/archive/2008/04/15/1153775.html&#xff09; WCF是.NET提供的一种服务&#xff0c;可以将自己写的程序&#xff08;完成特定功能&#xff0c;比如从数据库中读取数据操作等&#xff09…

WebService、WCF、WebAPI之间的区别

Web Service 1、它是基于SOAP协议的&#xff0c;数据格式是XML 2、只支持HTTP协议 3、它不是开源的&#xff0c;但可以被任意一个了解XML的人使用 4、它只能部署在IIS上 WCF 1、它是基于SOAP协议的&#xff0c;数据格式是XML 2、这个是Web Service&#xff08;ASMX&#xff09…

WCF 简介

一、WCF概述 1&#xff09; 什么是WCF&#xff1f; Windows Communication Foundation (WCF) 是用于构建面向服务的应用程序的框架。借助 WCF&#xff0c;可以将数据作为异步消息从一个服务终结点发送至另一个服务终结点。服务终结点可以是由 IIS 承载的持续可用的服务的一部分…

网络编程之WCF编程:WCF服务和客户端的建立,回调

1.概念 Windows Communication Foundation(WCF)是由微软发展的一组数据通信的应用程序开发接口&#xff0c;可以翻译为Windows通讯接口。它是.NET框架的一部分&#xff0c;由 .NET Framework 3.0 开始引入。 WCF的终结点有三个要素组成&#xff0c;分别是地址&#xff08;Add…

WCF 学习总结2 -- 配置WCF

前面一篇文章《WCF 学习总结1 -- 简单实例》一股脑儿展示了几种WCF部署方式&#xff0c;其中配置文件(App.config/Web.config)都是IDE自动生成&#xff0c;省去了我们不少功夫。现在回过头来看看IDE提供的Wcf Service Library项目模板中的默认服务端配置文件——App.config里面…

[老老实实学WCF] 第一篇 Hello WCF

老老实实学WCF 第一篇 Hello WCF WCF(Windows Communication Foundation)是微软公司推出的面向服务技术的集大成者&#xff0c;涵盖继承了其之前发布的所有的分布式应用程序的编程模型&#xff0c;涉及面之广&#xff0c;技术之复杂&#xff0c;结构之零散&#xff0c;让我们…

WCF入门教程(一)

WCF入门教程&#xff08;一&#xff09; 一、 概述二、基于Asp.net 的应用程序开发与面向服务开发三、第一个WCF程序IUser代码:User代码 四、场景五、将WCF程序寄宿在B服务器的IIS之上六、在客户端[A服务器]创建服务的引用七、使用WCF的方法九、代码下载 一、 概述 Windows Co…

WCF简介

WCF是Windows Communication Foundation的缩写&#xff0c;是MS为SOA&#xff08;Service Oriented Architecture 面向服务架构&#xff09;而设计的一套完整的技术框架。WCF是Microsoft为构建面向服务的应用提供的分布式通信编程框架,使用该框架&#xff0c;开发人员可以构建跨…

无废话WCF入门教程一[什么是WCF]

一、概述 Windows Communication Foundation(WCF)是由微软发展的一组数据通信的应用程序开发接口&#xff0c;可以翻译为Windows通讯接口&#xff0c;它是.NET框架的一部分。由 .NET Framework 3.0 开始引入。 WCF的最终目标是通过进程或不同的系统、通过本地网络或是通过Inter…

C# WCF入门

目录标题 一、什么是WCF二、第一个WCF程序三、WCF服务的使用 一、什么是WCF WCF是使用托管代码建立和运行面向服务(Service Oriented)应用程序的统一框架。它使得开发者能够建立一个跨平台的、安全、可信赖、事务性的解决方案&#xff0c;且能与已有系统兼容协作。WCF是微软分…

wcf学习--建立最简单的WCF服务

在VS2010里建立一个最简单的WCF服务&#xff0c;基本流程如下&#xff1a; 一&#xff1a;新建WCF应用 首先&#xff0c;新建一个WCF服务的应用&#xff08;这里以framework 4.0为例&#xff09;&#xff0c;如下图所示&#xff0c; 建立完成之后&#xff0c;VS将自动生成一个最…

什么是WCF

文章目录 一、概述二、基于Asp.net 的应用程序开发与面向服务开发三、第一个WCF程序四、场景五、将WCF程序寄宿在B服务器的IIS之上六、在客户端[A服务器]创建服务的引用七、使用WCF服务端的方法 一、概述 Windows Communication Foundation(WCF)是由微软发展的一组数据通信的应…

面向服务的WCF编程(一)

第七章&#xff1a;WCF入门 课后习题&#xff1a; 1.简要介绍WCF服务的承载方式及其特点。 WCF服务的承载方式包括&#xff1a;利用IIS或者WAS承载、利用Windows服务承载、自承载。其特点如下&#xff1a; &#xff08;1&#xff09;用IIS或者WAS承载&#xff1a;这是最常用…

WCF 详解

一、什么是WCF&#xff1f; ​ .NET Framework 3.0 中开始引入一种专门用来构建分布式系统的API——WCF&#xff0c;与过去所有的其他分布式API&#xff08;如DCOM,.NET Remoting,XML WebService,消息队列&#xff09;有所不同&#xff0c;WCF提供统一的&#xff0c;可扩展的编…

Windows内核原理与实现之 GDI (图形设备接口)

文章摘录自《Windows内核原理与实现》一书。 图形用户界面是 Windows 操作系统的重要特色&#xff0c;这也是在 Windows 子系统中提供的。概括而言&#xff0c;Windows 的图形系统有两方面特点&#xff1a;首先&#xff0c;它提供了一套与设备无关的编程接口&#xff0c;即 G…

windows 驱动与内核调试 学习

概述 本文讲述笔者在学习内核和驱动开发的笔记。 驱动概述 一般驱动需要运行内核权限下运行(因为涉及硬件读取)&#xff0c;比如Intel下的ring 0 权限下。在windwos大量病毒和杀软为了特殊目的往往都是通过将自身升级为内核驱动方式进行运作。如果病毒程序首先进入ring 0理论…

Windows内核--CPU和内核(1.7)

Windows内核支援哪些CPU? Intel x86/x86_64 IA64已不再支持. AMD amd64 ARM (Windows On Arm: WOA) ARM具备低功耗优势, 除了高通, 还有Broadcom/NXP等都支援ARM架构. 苹果自研M系列开了头&#xff0c;ARM不仅有低功耗&#xff0c;同样有性能&#xff0c;Windows也想分一杯羹…

windows内核驱动

内核&驱动基础 WDK(Windows Driver Kit) 内核编程需要使用WDK WDK 下载 windows xp wdk 下载地址 WDK 安装 勾选所有的安装项,避免错过一些例子 默认安装目录: C:\WinDDKfirst驱动开发 源码 first.c #include <ntddk.h>#define DEBUG/** 卸载函数*/ VOID Driver…

Windows 内核会换为 Linux 吗?

关注、星标公众号&#xff0c;不错过精彩内容 来源&#xff1a;网络 编辑整理&#xff1a;strongerHuang 如果装个纯linux&#xff0c;则一些windows软件没法用。如果用windows然后装个虚拟机&#xff0c;在虚拟机上安装linux&#xff0c;又感觉麻烦而且占用电脑资源。 现在win…

Windows内核之系统架构

一.架构概述 下图显示了Windows的基本结构。Windows采用双模式来保护操作系统本身&#xff0c;以避免被应用程序的错误所波及。操作系统核心运行在内核模式下&#xff0c;应用程序的代码运行在用户模式下。每当应用程序需要用到系统内核或内核的扩展模块&#xff08;内核驱动程…