您现在的位置是:网站首页> 编程资料编程资料
WCF中使用nettcp协议进行通讯的方法_实用技巧_
2023-05-24
281人已围观
简介 WCF中使用nettcp协议进行通讯的方法_实用技巧_
快速阅读
如何在wcf中用net tcp协议进行通讯,一个打开Wcf的公共类。比较好好,可以记下来。 配置文件中注意配置 Service,binding,behaviors. Service中配置endpoint 指明abc ,binding中配置tcp通讯的要关参数,behaivor中配置http请求的 地址
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绑定netTcpBinding寄宿到控制台应用程序:https://www.jb51.net/article/165257.htm
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。
相关内容
- .NET生成动态验证码的完整步骤_实用技巧_
- 3分钟快速学会在ASP.NET Core MVC中如何使用Cookie_实用技巧_
- ASP.NET Core 3.0 gRPC拦截器的使用_实用技巧_
- ASP.NET Core 3.0使用gRPC的具体方法_实用技巧_
- .NET Core3.1编写混合C++程序_实用技巧_
- ASP.NET实现图书管理系统的步骤详解_实用技巧_
- ASP.NET MVC 开发微信支付H5的实现示例(外置浏览器支付)_实用技巧_
- 详解MVC中为DropDownListFor设置选中项的方法_实用技巧_
- 详解ASP.NET MVC 下拉框的传值的两种方式_实用技巧_
- ASP.NET Core中快速构建PDF文档的步骤分享第1/2页_实用技巧_
