喂 我需要一个Tcp连接到一个在backgrond中活着的服务器,应用程序将使用此连接发送数据。我搜索了周围,发现WCF单例适用于此任务 这是我在下面使用的代码片段 我的问题是好的方法和任何问题都可能与此有关吗?
string hostAddress = string.Empty;
try
{
srvHost = new ServiceHost(typeof(ControllerClass));
NetTcpBinding netTcpBinding = new NetTcpBinding(SecurityMode.None);
netTcpBinding.Security.Message.ClientCredentialType = MessageCredentialType.None;
netTcpBinding.Security.Transport.ProtectionLevel = System.Net.Security.ProtectionLevel.None;
netTcpBinding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None;
srvHost.AddServiceEndpoint(typeof(IControllerContract), netTcpBinding, hostAddress);
srvHost.Credentials.WindowsAuthentication.AllowAnonymousLogons = true;
ServiceThrottlingBehavior serviceThrottlingBehavior = new ServiceThrottlingBehavior();
serviceThrottlingBehavior.MaxConcurrentCalls = 1000;
serviceThrottlingBehavior.MaxConcurrentInstances = 1000;
serviceThrottlingBehavior.MaxConcurrentSessions = 1000;
srvHost.Description.Behaviors.Add(serviceThrottlingBehavior);
srvHost.Open();
}
catch (System.TimeoutException timeoutEx)
{
Thread.Sleep(1000);
ReOpenHostConnection();//initialize again Controller Class
}
catch (Exception ex)
{
Trace.WriteLine(string.Format("cannot start Service Ex:{0}", ex.ToString()), TraceEventType.Error.ToString());
}
//Controller Class Initialize Code Snippet
TcpClient iTcpClient = new TcpClient();
iTcpClient.Connect(serverIP, serverPort);
networkStream = iTcpClient.GetStream();
aSychDataByte = new byte[iTcpClient.ReceiveBufferSize];
networkStream.BeginRead(aSychDataByte, 0, incommTcpClient.ReceiveBufferSize, ReadAsych, null);
答案 0 :(得分:0)
为什么要将TcpClient与WCF结合使用?如果您需要基于低级别Tcp类的低级别Tcp通信构建客户端和服务器。如果您需要服务而且不打扰消息格式,请使用WCF。
为了你的问题。你不需要单身人士。您只需要打开连接即可。为此,您需要在客户端上创建WCF代理实例(开放通道)并调用该服务。它将创建与服务实例的连接,直到您关闭客户端代理,直到您的服务主机停止工作或超时(默认情况下客户端不活动10分钟)。