在WCF服务中自动重新连接

时间:2012-04-22 18:11:10

标签: wcf c#-4.0 client-server

我有一台服务器,它从多个系统接收数据,将它们添加到数据库并使用最新接收的数据更新另一个应用程序(客户端)。此客户端(均在同一台计算机上运行)以有组织的形式显示数据并对其进行一些处理。而且,它可以使用服务器在数据库中执行查询。因此它使用服务器中的函数来获取历史数据。

对于此通信,我使用的是WCF,服务器在.config中声明如下:

  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service name="ServiceName">
        <endpoint binding="netTcpBinding" contract="IServiceName">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange"/>
        <host>
          <baseAddresses>
            <add baseAddress="net.tcp://localhost:5050/msservice"/>
          </baseAddresses>
        </host>
      </service>
    </services>
  </system.serviceModel>

客户端使用以下配置:

<system.serviceModel>
    <bindings>
        <netTcpBinding>
            <binding name="NetTcpBinding_IService" closeTimeout="00:02:00" openTimeout="00:02:00" receiveTimeout="00:10:00" sendTimeout="00:02:00" transactionFlow="false" transferMode="Buffered" transactionProtocol="OleTransactions" hostNameComparisonMode="StrongWildcard" listenBacklog="10" maxConnections="10" maxBufferSize="2147483647" maxBufferPoolSize="2147483647">
                <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false"/>
                <security mode="Transport">
                    <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign"/>
                    <message clientCredentialType="Windows"/>
                </security>
            </binding>
        </netTcpBinding>
    </bindings>
    <client>
        <endpoint address="net.tcp://localhost:5050/msservice" binding="netTcpBinding" bindingConfiguration="NetTcpBinding_IService" contract="Server.IService" name="NetTcpBinding_IService">
            <identity>
                <dns value="localhost"/>
            </identity>
        </endpoint>
    </client>
</system.serviceModel>

当客户端创建服务(连接到服务器)时,它使用名为Subscribe的服务功能,其中包括服务器连接客户端列表中的客户端。当新数据到达时,它会在所有客户端中引发一个事件。

然而,在客户端一些不活动之后(因为它不会定期向服务器发送消息,即使相反的情况发生频率非常高),它也会进入故障状态。发生这种情况时,服务器函数的每个客户端调用都会引发异常。

我希望,无论是在服务器端还是在客户端,每当通道关闭时自动重新连接,以保证客户端仍然从客户端接收消息,并且客户端的函数调用由服务器执行

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

负载平衡器在1分钟后关闭空闲连接。因此,如果你想保持连接存在,那么应该总是进行一些沟通

1)第一个选择是每分钟调用一次操作。

2)如果无法做到,那么

  • 在绑定上启用可靠消息传递,WCF基础架构将处理它。
  • 您可以配置inactivityTimeout和receiveTimeout以确保通道保持打开状态。
  • 如果任何一个超时,则必须设置两个超时,否则通道会出现故障。
  • 在可靠的会话配置之后,如果连接变为空闲,WCF将生成流量以使其保持打开状态。
相关问题