惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

P
Privacy & Cybersecurity Law Blog
Vercel News
Vercel News
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
N
Netflix TechBlog - Medium
罗磊的独立博客
F
Fortinet All Blogs
T
Threatpost
Y
Y Combinator Blog
博客园_首页
美团技术团队
Security Latest
Security Latest
博客园 - 三生石上(FineUI控件)
T
Tailwind CSS Blog
V
V2EX - 技术
The Cloudflare Blog
L
LINUX DO - 热门话题
博客园 - 司徒正美
Jina AI
Jina AI
P
Proofpoint News Feed
宝玉的分享
宝玉的分享
C
CXSECURITY Database RSS Feed - CXSecurity.com
C
Cybersecurity and Infrastructure Security Agency CISA
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
WordPress大学
WordPress大学
The Hacker News
The Hacker News
P
Privacy International News Feed
T
The Exploit Database - CXSecurity.com
Scott Helme
Scott Helme
有赞技术团队
有赞技术团队
V
V2EX
Stack Overflow Blog
Stack Overflow Blog
M
MIT News - Artificial intelligence
Latest news
Latest news
NISL@THU
NISL@THU
Google DeepMind News
Google DeepMind News
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
C
Cisco Blogs
雷峰网
雷峰网
Application and Cybersecurity Blog
Application and Cybersecurity Blog
B
Blog RSS Feed
W
WeLiveSecurity
D
DataBreaches.Net
G
Google Developers Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
G
GRAHAM CLULEY
Spread Privacy
Spread Privacy
Know Your Adversary
Know Your Adversary
TaoSecurity Blog
TaoSecurity Blog
S
Securelist
Help Net Security
Help Net Security

博客园 - 水木

为什么要监控sql语句,以及如何监控,都有哪几种方式可以监控。 关于hexo与github使用过程中的问题与笔记 - 水木 - 博客园 IIS错误代码500.21 ,Nhibernate更新报错,委托的使用。action传参数 mysql 使用的三个小技巧 利用反向代理服务器,加快国内对国外主机的访问 - 水木 2019年七月第三周总结 ManualResetEven使用的最清楚说明 如何画数据流图 如何画好ER图 UML图中时序图的基本用法 系统架构设计上需要注意的 weblogic介绍 - 水木 - 博客园 Tuxedo 介绍 winform如何不卡界面 银行基金代销系统调研 20190710用控制台启动一个wcf服务 wcf必知必会以及与Webapi的区别 - 水木 2019年7月第一周总结-RabbitMQ总结 RabbitMQ入门学习系列(七) 远程调用RPC
如何在wcf中用net tcp协议进行通讯
水木 · 2019-07-12 · via 博客园 - 水木

快速阅读

如何在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<TService>: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<TService>();
                    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请求的 地址

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <services>
      <service name="hcbServiceB.User"  behaviorConfiguration="userBehavior">
        <endpoint address="net.tcp://localhost:12345/User" binding="netTcpBinding" contract="hcbServiceB.IUser">
          <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="userBehavior">
          <serviceMetadata httpGetEnabled="True" httpGetUrl="http://localhost:8081/User" />
          <serviceDebug includeExceptionDetailInFaults="True" />
          <serviceThrottling maxConcurrentCalls="1000" maxConcurrentInstances="1000" maxConcurrentSessions="1000" />
        </behavior>
        
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

</configuration>

4.启动服务

控制台中启动服务

 static void Main(string[] args)
 {
     Console.WriteLine("初始化...");
     Console.WriteLine("服务运行期间,请不要关闭窗口。");
     Console.Title = "wcf net tcp测试 ";
     var cancelTokenSouce = new CancellationTokenSource();
     ServiceHostManager<User>.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.cnblogs.com/felixnet/p/7397139.html

友情提示

​ 我对我的文章负责,发现好多网上的文章 没有实践,都发出来的,让人走很多弯路,如果你在我的文章中遇到无法实现,或者无法走通的问题。可以直接在公众号《爱码农爱生活 》留言。必定会再次复查原因。让每一篇 文章的流程都能顺利实现。