WCF如何绑定netTcpBinding寄宿到控制台应用程序详解

简介: 新建一个WCF服务类库项目,在其中添加两个WCF服务:GameService,PlayerService

契约

新建一个WCF服务类库项目,在其中添加两个WCF服务:GameService,PlayerService

网络异常,图片无法展示
|

代码如下:

[ServiceContract]

public interface IGameService

{

[OperationContract]

Task<string> DoWork(string arg);

}

public class GameService : IGameService

{

public async Task<string> DoWork(string arg)

{

 return await Task.FromResult($"Hello {arg}, I am the GameService.");

}

}

[ServiceContract]

public interface IPlayerService

{

[OperationContract]

Task<string> DoWork(string arg);

}

public class PlayerService : IPlayerService

{

public async Task<string> DoWork(string arg)

{

 return await Task.FromResult($"Hello {arg}, I am the PlayerService.");

}

}

服务端

新建一个控制台应用程序,添加一个类 ServiceHostManager

public interface IServiceHostManager : IDisposable

{

void Start();

void Stop();

}


public class ServiceHostManager<TService> : IServiceHostManager

where TService : class

{

ServiceHost _host;


public ServiceHostManager()

{

 _host = new ServiceHost(typeof(TService));

 _host.Opened += (s, a) => {

  Console.WriteLine("WCF监听已启动!{0}", _host.Description.Endpoints[0].Address);

 };

 _host.Closed += (s, a) =>

 {

  Console.WriteLine("WCF服务已终止!{0}", _host.Description.Endpoints[0].Name);

 };  

}

public void Start()

{

 Console.WriteLine("正在开启WCF服务...{0}", _host.Description.Endpoints[0].Name);

 _host.Open();

}

public void Stop()

{

 if (_host != null && _host.State == CommunicationState.Opened)

 {

  Console.WriteLine("正在关闭WCF服务...{0}", _host.Description.Endpoints[0].Name);

  _host.Close();

 }

}

public void Dispose()

{

 Stop();

}


public static Task StartNew(CancellationTokenSource cancelTokenSource)

{

 var theTask = Task.Factory.StartNew(() =>

 {

  IServiceHostManager shs = null;

  try

  {

   shs = new ServiceHostManager<TService>();

   shs.Start();

   while (true)

   {

    if (cancelTokenSource.IsCancellationRequested && shs != null)

    {

     shs.Stop();

     break;

    }

   }

  }

  catch (Exception ex)

  {

   Console.WriteLine(ex);

   if (shs != null)

    shs.Stop();

  }

 }, cancelTokenSource.Token);


 return theTask;

}

}

在Main方法中启动WCF主机

class Program

{

 static Program()

 {

  Console.WriteLine("初始化...");

  Console.WriteLine("服务运行期间,请不要关闭窗口。");

  Console.WriteLine();

 }


 static void Main(string[] args)

 {

  Console.Title = "WCF主机 x64.(按 [Esc] 键停止服务)";

  var cancelTokenSource = new CancellationTokenSource();

  ServiceHostManager<WcfContract.Services.GameService>.StartNew(cancelTokenSource);

  ServiceHostManager<WcfContract.Services.PlayerService>.StartNew(cancelTokenSource);

  while (true)

  {

   if (Console.ReadKey().Key == ConsoleKey.Escape)

   {

    Console.WriteLine();

    cancelTokenSource.Cancel();

    break;

   }

  }

  Console.ReadLine();

 }

}

服务端配置

在控制台应用程序的App.config中配置system.serviceModel

<system.serviceModel>

<services>

 <service name="Wettery.WcfContract.Services.GameService" behaviorConfiguration="gameMetadataBehavior">

 <endpoint address="net.tcp://localhost:19998/Wettery/GameService" binding="netTcpBinding" contract="Wettery.WcfContract.Services.IGameService" bindingConfiguration="netTcpBindingConfig">

  <identity>

  <dns value="localhost" />

  </identity>

 </endpoint>

 </service>

 <service name="Wettery.WcfContract.Services.PlayerService" behaviorConfiguration="playerMetadataBehavior">

 <endpoint address="net.tcp://localhost:19998/Wettery/PlayerService" binding="netTcpBinding" contract="Wettery.WcfContract.Services.IPlayerService" bindingConfiguration="netTcpBindingConfig">

  <identity>

  <dns value="localhost" />

  </identity>

 </endpoint>

 </service>

</services>

<bindings>

 <netTcpBinding>

 <binding name="netTcpBindingConfig" closeTimeout="00:30:00" openTimeout="00:30:00" receiveTimeout="00:30:00" sendTimeout="00:30:00" transactionFlow="false" transferMode="Buffered" transactionProtocol="OleTransactions" hostNameComparisonMode="StrongWildcard" listenBacklog="100" maxBufferPoolSize="2147483647" maxBufferSize="2147483647" maxConnections="100" maxReceivedMessageSize="2147483647">

  <readerQuotas maxDepth="64" maxStringContentLength="2147483647" maxArrayLength="2147483647 " maxBytesPerRead="4096" maxNameTableCharCount="16384" />

  <reliableSession ordered="true" inactivityTimeout="00:30:00" enabled="false" />

  <security mode="Transport">

  <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />

  </security>

 </binding>

 </netTcpBinding>

</bindings>

<behaviors>

 <serviceBehaviors>

 <behavior name="gameMetadataBehavior">

  <serviceMetadata httpGetEnabled="True" httpGetUrl="http://localhost:8081/Wettery/GameService/MetaData" />

  <serviceDebug includeExceptionDetailInFaults="True" />

  <serviceThrottling maxConcurrentCalls="1000" maxConcurrentInstances="1000" maxConcurrentSessions="1000" />

 </behavior>

 <behavior name="playerMetadataBehavior">

  <serviceMetadata httpGetEnabled="True" httpGetUrl="http://localhost:8081/Wettery/PlayerService/MetaData" />

  <serviceDebug includeExceptionDetailInFaults="True" />

  <serviceThrottling maxConcurrentCalls="1000" maxConcurrentInstances="1000" maxConcurrentSessions="1000" />

 </behavior>

 </serviceBehaviors>

</behaviors>

</system.serviceModel>

未避免元数据泄露,部署时将HttpGetEnable设为False

运行控制台应用程序

网络异常,图片无法展示
|
按[ESC]键终止服务

网络异常,图片无法展示
|

客户端测试

服务端运行后,用wcftestclient工具测试,服务地址即behavior中配置的元数据GET地址

http://localhost:8081/Wettery/GameService/MetaData

http://localhost:8081/Wettery/PlayerService/MetaData

网络异常,图片无法展示
|

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,米米素材网谢谢大家的支持。

相关文章
|
3天前
|
存储 运维 Serverless
Serverless 应用引擎产品使用之阿里函数计算中返回函数计算2.0控制台如何解决
阿里云Serverless 应用引擎(SAE)提供了完整的微服务应用生命周期管理能力,包括应用部署、服务治理、开发运维、资源管理等功能,并通过扩展功能支持多环境管理、API Gateway、事件驱动等高级应用场景,帮助企业快速构建、部署、运维和扩展微服务架构,实现Serverless化的应用部署与运维模式。以下是对SAE产品使用合集的概述,包括应用管理、服务治理、开发运维、资源管理等方面。
13 1
|
10月前
phpstorm插件应用:Test RESTful WEB Service 控制台接口调试工具
phpstorm插件应用:Test RESTful WEB Service 控制台接口调试工具
119 0
|
运维 Kubernetes Linux
【Kubernetes】 Dashboard 控制台web部署应用
相比kubectl命令和yaml文件配置部署,图形化部署更简单,但是作为k8s运维,还是需要掌握yaml编写配置
844 0
【Kubernetes】 Dashboard 控制台web部署应用
|
2月前
|
Web App开发 缓存 运维
应用研发平台EMAS产品常见问题之emas控制台访问非常慢如何解决
应用研发平台EMAS(Enterprise Mobile Application Service)是阿里云提供的一个全栈移动应用开发平台,集成了应用开发、测试、部署、监控和运营服务;本合集旨在总结EMAS产品在应用开发和运维过程中的常见问题及解决方案,助力开发者和企业高效解决技术难题,加速移动应用的上线和稳定运行。
.Net Core控制台应用程序使用定时器
.Net Core控制台应用程序使用定时器
274 0
.Net Core控制台应用程序使用定时器
|
开发框架 .NET 数据库连接
WCF基础教程——vs2013创建wcf应用程序
WCF基础教程——vs2013创建wcf应用程序
152 0
WCF基础教程——vs2013创建wcf应用程序
|
前端开发 JavaScript Java
Sentinel 控制台项目应用的启动 | 学习笔记
快速学习 Sentinel 控制台项目应用的启动
175 0
Sentinel 控制台项目应用的启动 | 学习笔记
|
API 微服务
如何使用 SAP Kyma 控制台手动发送 SAP Commerce Cloud Mock 应用暴露的事件
如何使用 SAP Kyma 控制台手动发送 SAP Commerce Cloud Mock 应用暴露的事件
123 0
如何使用 SAP Kyma 控制台手动发送 SAP Commerce Cloud Mock 应用暴露的事件
|
Java 专有云 Spring
专有云Spring Cloud应用限流降级--Series3:配置控制台规则
专有云Spring Cloud应用限流降级--Series3:配置控制台规则
专有云Spring Cloud应用限流降级--Series3:配置控制台规则
|
1月前
|
Java 数据库 Android开发
图书销售系统【纯控制台】(Java课设)
图书销售系统【纯控制台】(Java课设)
23 1