Communication method using nettcp protocol in WCF

Time:2020-6-14

Fast reading

How to use net TCP protocol to communicate in WCF, a public class to open WCF. It’s better. You can write it down. In the configuration file, pay attention to the configuration of Service, binding and behaviors. in the Service, the configuration of endpoint indicates ABC, the configuration of TCP communication parameters in the binding, and the configuration of HTTP request address in the behaivor

1. Establish service server

Use the last code to provide a user class and implement a method


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

2. Servicehostmanager public class

Public classes can reduce the amount of code writing, which can be saved and used directly in the future

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 service has started listening {0}", host.Description.Endpoints [0].Address);
  };
  host.Closed+= (sender, e) =>
  {
  Console.WriteLine ("WCF service started shutting down {0}", host.Description.Endpoints [0].Address);
  };
 } 
 public void Start()
 {
  Console.WriteLine ("starting WCF service {0}", host.Description.Endpoints [0].Name);
  host.Open();
 }

 public void Stop()
 {
  if (host != null && host.State == CommunicationState.Opened)
  {
  Console.WriteLine ("shutting down WCF service {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. Configuration related parameters

In the configuration file, pay attention to the configuration of Service, binding and behaviors. in the Service, the configuration of endpoint indicates ABC, the configuration of TCP communication parameters in the binding, and the configuration of HTTP request address in the behaivor


<?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. Start service

Start service in console

static void Main(string[] args)
 {
 Console.WriteLine ("initialize...");
 Console.WriteLine ("please do not close the window while the service is running. "";
 Console.Title  ="WCF net TCP test";
 var cancelTokenSouce = new CancellationTokenSource();
 ServiceHostManager<User>.StartNew(cancelTokenSouce);
 while (true)
 {
  if (Console.ReadKey().Key == ConsoleKey.Escape)
  {
  Console.WriteLine();
  cancelTokenSouce.Cancel();
  break;
  }
 }
 }

5 wcftesttools software test

The software path is located in. You can find it according to the directory where you installed vs.
D:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE

test

reference resources:

WCF binding NetTcpBinding to host to console application: https://www.jb51.net/article/165257.htm

summary

The above is the whole content of this article. I hope that the content of this article has some reference learning value for your study or work. Thank you for your support for developepaer.

Recommended Today

A text to clarify the context in JavaScript

background This article is part of “in 2019, after reading this one, I will no longer be afraid of the front-end interview” Refer to what I wrote beforeBlogAnd extradata, share it to you, hope to bring some to youInspiration and help。 For reprint, please contact the author for permission. text contextIt is an important concept […]