开发者

Hold TcpClient Connection with WCF

Hallo I need a Tcp connection to a server alive in backgrond and applications will send data with this connection.I searched around and found WCF singleton is apporiate for this task here is a code snippet that i use below my question is that the good way and any problem can be with this?

 string hostAddress = string.Empty;
           try
            {
     开发者_StackOverflow社区           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);


Why do you combine TcpClient with WCF? If you need low level Tcp communication build client and server based on low level Tcp classes. If you need service and you don't bother with message formats use WCF.

For your problem. You don't need singleton. You just need the connection to be opened. For this you need to create WCF proxy instance (open channel) on the client and call the service. It will create connection to service instance wich will live until you close the client proxy, until your service host stops working or until timeout (10 minutes of client inactivity by default).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜