Как включить TCP на локальной сети - PullRequest
0 голосов
/ 16 октября 2011

Я написал код для моего приложения WPF для использования WCF, wcf работает как служба Windows, я хочу, чтобы программа wpf работала на клиентских компьютерах.Я установил приложение WPF на ПК вместе со службой и сервером sql, там все работает нормально.Однако, когда я установил wpf-клиент на другом ПК, клиентский WPF не может подключиться к серверу.Я имею в виду, что служба Windows WCF не поддерживает использование локальной сети, однако я разработала ее только для этого.Пожалуйста, проверьте мой код и скажите, где я ошибся.

Код приложения WPF:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
            <section name="WorkMateWPF.MySettings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
        </sectionGroup>
    </configSections>
    <system.diagnostics>
        <sources>
            <!-- This section defines the logging configuration for My.Application.Log -->
            <source name="DefaultSource" switchName="DefaultSwitch">
                <listeners>
                    <add name="FileLog"/>
                    <!-- Uncomment the below section to write to the Application Event Log -->
                    <!--<add name="EventLog"/>-->
                </listeners>
            </source>
        </sources>
        <switches>
            <add name="DefaultSwitch" value="Information" />
        </switches>
        <sharedListeners>
            <add name="FileLog"
                 type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
                 initializeData="FileLogWriter"/>
            <!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
            <!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> -->
        </sharedListeners>
    </system.diagnostics>
    <system.serviceModel>
        <bindings>
            <netTcpBinding>
                <binding name="NetTcpBinding_IWCFBatchImport" closeTimeout="00:01:00"
                    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                    transactionFlow="false" transferMode="Buffered" transactionProtocol="OleTransactions"
                    hostNameComparisonMode="StrongWildcard" listenBacklog="10"
                    maxBufferPoolSize="524288" maxBufferSize="65536" maxConnections="10"
                    maxReceivedMessageSize="65536">
                    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                    <reliableSession ordered="true" inactivityTimeout="00:10:00"
                        enabled="false" />
                    <security mode="Transport">
                        <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
                        <message clientCredentialType="Windows" />
                    </security>
                </binding>
                <binding name="NetTcpBinding_IWCFCourses" closeTimeout="00:01:00"
                    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                    transactionFlow="false" transferMode="Buffered" transactionProtocol="OleTransactions"
                    hostNameComparisonMode="StrongWildcard" listenBacklog="10"
                    maxBufferPoolSize="524288" maxBufferSize="65536" maxConnections="10"
                    maxReceivedMessageSize="65536">
                    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                    <reliableSession ordered="true" inactivityTimeout="00:10:00"
                        enabled="false" />
                    <security mode="Transport">
                        <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
                        <message clientCredentialType="Windows" />
                    </security>
                </binding>
                <binding name="NetTcpBinding_IWCFFaculty" closeTimeout="00:01:00"
                    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                    transactionFlow="false" transferMode="Buffered" transactionProtocol="OleTransactions"
                    hostNameComparisonMode="StrongWildcard" listenBacklog="10"
                    maxBufferPoolSize="524288" maxBufferSize="65536" maxConnections="10"
                    maxReceivedMessageSize="65536">
                    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                    <reliableSession ordered="true" inactivityTimeout="00:10:00"
                        enabled="false" />
                    <security mode="Transport">
                        <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
                        <message clientCredentialType="Windows" />
                    </security>
                </binding>
                <binding name="NetTcpBinding_IWCFLogin" closeTimeout="00:01:00"
                    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                    transactionFlow="false" transferMode="Buffered" transactionProtocol="OleTransactions"
                    hostNameComparisonMode="StrongWildcard" listenBacklog="10"
                    maxBufferPoolSize="524288" maxBufferSize="65536" maxConnections="10"
                    maxReceivedMessageSize="65536">
                    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                    <reliableSession ordered="true" inactivityTimeout="00:10:00"
                        enabled="false" />
                    <security mode="Transport">
                        <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
                        <message clientCredentialType="Windows" />
                    </security>
                </binding>
                <binding name="NetTcpBinding_IWCFStudent" closeTimeout="00:01:00"
                    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                    transactionFlow="false" transferMode="Buffered" transactionProtocol="OleTransactions"
                    hostNameComparisonMode="StrongWildcard" listenBacklog="10"
                    maxBufferPoolSize="524288" maxBufferSize="65536" maxConnections="10"
                    maxReceivedMessageSize="65536">
                    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                    <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:8732/WCFBatchImports"
                binding="netTcpBinding" bindingConfiguration="NetTcpBinding_IWCFBatchImport"
                contract="ServiceBatchImports.IWCFBatchImport" name="NetTcpBinding_IWCFBatchImport">
                <identity>
                    <dns value="localhost" />
                </identity>
            </endpoint>
            <endpoint address="net.tcp://localhost:8732/WCFCourses" binding="netTcpBinding"
                bindingConfiguration="NetTcpBinding_IWCFCourses" contract="ServiceCourses.IWCFCourses"
                name="NetTcpBinding_IWCFCourses">
                <identity>
                    <dns value="localhost" />
                </identity>
            </endpoint>
            <endpoint address="net.tcp://localhost:8732/WCFFaculty" binding="netTcpBinding"
                bindingConfiguration="NetTcpBinding_IWCFFaculty" contract="ServiceFaculty.IWCFFaculty"
                name="NetTcpBinding_IWCFFaculty">
                <identity>
                    <dns value="localhost" />
                </identity>
            </endpoint>
            <endpoint address="net.tcp://localhost:8732/WCFLogin" binding="netTcpBinding"
                bindingConfiguration="NetTcpBinding_IWCFLogin" contract="ServiceLogins.IWCFLogin"
                name="NetTcpBinding_IWCFLogin">
                <identity>
                    <dns value="localhost" />
                </identity>
            </endpoint>
            <endpoint address="net.tcp://localhost:8732/WCFStudents" binding="netTcpBinding"
                bindingConfiguration="NetTcpBinding_IWCFStudent" contract="ServiceStudents.IWCFStudent"
                name="NetTcpBinding_IWCFStudent">
                <identity>
                    <dns value="localhost" />
                </identity>
            </endpoint>
        </client>
    </system.serviceModel>
    <userSettings>
        <WorkMateWPF.MySettings>
            <setting name="Test" serializeAs="String">
                <value />
            </setting>
        </WorkMateWPF.MySettings>
    </userSettings>
</configuration>

Ниже приведен код приложения службы:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <configSections>
  </configSections>
  <connectionStrings>
    <add name="WorkMateWCF.My.MySettings.workmateConnectionString"
      connectionString="Data Source=PAVAN-PC;Initial Catalog=WorkMate;Persist Security Info=True;User ID=WorkMateUser;Password=workmateuser"
      providerName="System.Data.SqlClient" />
  </connectionStrings>
  <system.web>
    <compilation debug="true" />
  </system.web>
  <!-- When deploying the service library project, the content of the config file must be added to the host's 
  app.config file. System.Configuration does not support config files for libraries. -->
  <system.serviceModel>
    <services>
      <service name="WorkMateWCF.WCFLogin">
        <endpoint address="" binding="netTcpBinding" bindingConfiguration=""
          contract="WorkMateWCF.IWCFLogin">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexTcpBinding" bindingConfiguration=""
          contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="net.tcp://localhost:8732/WCFLogin" />
          </baseAddresses>
        </host>
      </service>
      <service name="WorkMateWCF.WCFCourses">
        <endpoint address="" binding="netTcpBinding" bindingConfiguration=""
          contract="WorkMateWCF.IWCFCourses">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexTcpBinding" bindingConfiguration=""
          contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="net.tcp://localhost:8732/WCFCourses" />
          </baseAddresses>
        </host>
      </service>
      <service name="WorkMateWCF.WCFStudent">
        <endpoint address="" binding="netTcpBinding" bindingConfiguration=""
          contract="WorkMateWCF.IWCFStudent">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexTcpBinding" bindingConfiguration=""
          contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="net.tcp://localhost:8732/WCFStudents" />
          </baseAddresses>
        </host>
      </service>
      <service name="WorkMateWCF.WCFBatchImport">
        <endpoint address="" binding="netTcpBinding" bindingConfiguration=""
          contract="WorkMateWCF.IWCFBatchImport">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexTcpBinding" bindingConfiguration=""
          contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="net.tcp://localhost:8732/WCFBatchImports" />
          </baseAddresses>
        </host>
      </service>
      <service name="WorkMateWCF.WCFFaculty">
        <endpoint address="" binding="netTcpBinding" bindingConfiguration=""
          contract="WorkMateWCF.IWCFFaculty">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexTcpBinding" bindingConfiguration=""
          contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="net.tcp://localhost:8732/WCFFaculty" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="false" httpsGetEnabled="false" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

</configuration>

С нетерпением ждем необходимости.Спасибо.

Ответы [ 2 ]

1 голос
/ 16 октября 2011

Похоже, что все ваши сервисные адреса установлены на localhost, как в сервисных, так и в клиентских конфигурационных файлах.Локальный хост всегда относится к машине, на которой выполняется программа.

Вам нужно будет использовать правильное имя машины для службы и ссылаться на него в клиенте.

Например, например, ваша службаразмещен на компьютере в сети со следующим адресом - myservicebox: 8732.Файл конфигурации службы будет выглядеть следующим образом:

<service name="WorkMateWCF.WCFLogin">
  <endpoint address="" binding="netTcpBinding" bindingConfiguration=""
            contract="WorkMateWCF.IWCFLogin">
    <identity>
      <dns value="myservicebox" />
    </identity>
  </endpoint>
  <endpoint address="mex" binding="mexTcpBinding" bindingConfiguration=""
            contract="IMetadataExchange" />
    <host>
      <baseAddresses>
        <add baseAddress="net.tcp://myservicbox:8732/WCFLogin" />
      </baseAddresses>
    </host>
  </service>

Затем вы указали бы net.tcp://myservicebox:8732/WCFLogin в ваших клиентах, которые хотят использовать службу.

Также обратите внимание, что ваша служба(основываясь на опубликованном вами файле конфигурации) будет использовать значения по умолчанию для указанных привязок, что может вызвать проблемы для вас, если вам нужны другие значения (например, больший размер сообщения и т. д.).

Ваша клиентская конфигурация будет использовать настроенные вами привязки при назначении их клиентским конечным точкам с помощью атрибута bindingConfiguration.

Не обязательно проблема в вашем случае (и она выглядиткак будто вы используете значения по умолчанию на клиенте в любом случае, с первого взгляда), но кое-что нужно знать.

0 голосов
/ 18 октября 2011

Я позже проверил журналы событий, и проблема была со временем на привязке, и я изменил его на 00:10:00, и это, кажется, работает, но на этот раз я обнаружил новую ошибку, и это не относится к этомувопрос.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...