RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
怎么在WCF中使用nettcp协议实现通讯-创新互联

怎么在WCF中使用nettcp协议实现通讯?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

创新互联成立与2013年,是专业互联网技术服务公司,拥有项目网站设计制作、成都做网站网站策划,项目实施与项目整合能力。我们以让每一个梦想脱颖而出为使命,1280元呼中做网站,已为上家服务,为呼中各地企业和个人服务,联系电话:18982081108

1.建立服务服务端


还是用上次的代码,提供一个user类,实现一个方法

[ServiceContract]
 public interface IUser
 {
 [OperationContract]
 string GetUserInfo();
 }
[ServiceContract]
 public interface IUser
 {
 [OperationContract]
 string GetUserInfo();
 }

2.ServiceHostManager公有类


通过公有类可以减少代码编写量,可以保存下来,以后用的时候 直接拿来用

public interface IServiceHostmanager : IDisposable
 {
 void Start();
 void Stop();
 }

 public class ServiceHostManager:IServiceHostmanager 
 where TService:class
 {
 private ServiceHost host;
 public void Dispose()
 {
  Stop();
 }

 public ServiceHostManager()
 {
  host=new ServiceHost(typeof(User));
  host.Opened+= (sender, e) =>
  {
  Console.WriteLine("wcf服务已经启动监听{0}",host.Description.Endpoints[0].Address);
  };
  host.Closed+= (sender, e) =>
  {
  Console.WriteLine("wcf服务已经启动关闭{0}", host.Description.Endpoints[0].Address);
  };
 } 
 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 static Task StartNew(CancellationTokenSource conTokenSource)
 {
  var task = Task.Factory.StartNew(() =>
  {
  IServiceHostmanager shm = null;
  try
  {
   shm = new ServiceHostManager();
   shm.Start();
   while (true)
   {
   if (conTokenSource.IsCancellationRequested && shm != null)
   {
    shm.Stop();
    break;
   }
   }
  }
  catch (Exception ex)
  {
   Console.WriteLine(ex.Message);
   if (shm != null) shm.Stop();
  }
  },conTokenSource.Token);
  return task;
 }
 }

3.配置的相关参数


配置文件中注意配置 Service,binding,behaviors. Service中配置endpoint 指明abc ,binding中配置tcp通讯的要关参数,behaivor中配置http请求的 地址



 
 
 
 
  
  
  
 
 
 
 
 
 
  
  
  
  
  
 
 
 
 
 
 
  
  
  
 
 
 
 
 

4.启动服务


控制台中启动服务

 static void Main(string[] args)
 {
 Console.WriteLine("初始化...");
 Console.WriteLine("服务运行期间,请不要关闭窗口。");
 Console.Title = "wcf net tcp测试 ";
 var cancelTokenSouce = new CancellationTokenSource();
 ServiceHostManager.StartNew(cancelTokenSouce);
 while (true)
 {
  if (Console.ReadKey().Key == ConsoleKey.Escape)
  {
  Console.WriteLine();
  cancelTokenSouce.Cancel();
  break;
  }
 }
 }

5wcftesttoos软件测试


软件路径位于,可以根据自己安装vs的目录去找。
D:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE


测试

怎么在WCF中使用nettcp协议实现通讯


关于怎么在WCF中使用nettcp协议实现通讯问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注创新互联行业资讯频道了解更多相关知识。


分享标题:怎么在WCF中使用nettcp协议实现通讯-创新互联
标题链接:http://cqwzjz.cn/article/cdsgjg.html