Вызов метода дуплексного сервиса wcf из uwp не имеет никакого эффекта - PullRequest
0 голосов
/ 23 января 2019

Я разрабатываю приложение UWP, которое использует дуплексный сервис wcf, созданный мной. Проблема возникает, когда я пытаюсь вызвать метод из службы, буквально метод не запускается, и ни одна точка останова в коде службы не достигнута.

Это моя конфигурация в хост-приложении

<system.serviceModel>
  <services>
    <service name="WcfService.Services.ImageExchangeService" behaviorConfiguration="behaviorConfig">
      <endpoint address="net.tcp://localhost:4322/WcfService/Services/ImageExchangeService/tcp" binding="netTcpBinding" contract="WcfService.Services.IImageExchangeService" bindingConfiguration="tcpBinding"></endpoint>
      <endpoint address="net.tcp://localhost:4323/WcfService/Services/ImageExchangeService/mex" binding="mexTcpBinding" contract="IMetadataExchange" />
      <host>
        <baseAddresses>
          <add baseAddress="http://localhost:4321/WcfService/Services/ImageExchangeService" />
        </baseAddresses>
      </host>
    </service>
  </services>  
    <behaviors>
  <serviceBehaviors>
    <behavior name="behaviorConfig">
      <!-- To avoid disclosing metadata information, 
        set the values below to false before deployment -->
      <serviceMetadata httpGetEnabled="True" httpsGetEnabled="True"/>
      <!-- To receive exception details in faults for debugging purposes, 
        set the value below to true.  Set to false before deployment 
        to avoid disclosing exception information -->
      <serviceDebug includeExceptionDetailInFaults="False" />
    </behavior>
  </serviceBehaviors>
</behaviors>
<bindings>
  <netTcpBinding>
    <binding name="tcpBinding">
      <security mode="None"></security>
      <reliableSession enabled="true"/>
    </binding>
  </netTcpBinding>
</bindings>
</system.serviceModel>

Это мой сервисный интерфейс

    [ServiceContract(CallbackContract = typeof(IImageExchangeClient), SessionMode =SessionMode.Required)]
    public interface IImageExchangeService
    {
        [OperationContract(IsOneWay = true)]
        void Connect(string deviceIdentifier); 
    }

Это моя реализация интерфейса выше

  [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single, IncludeExceptionDetailInFaults =true)]
    public class ImageExchangeService : IImageExchangeService
    {
        private Dictionary<string, IImageExchangeClient> _connectedDevices = new Dictionary<string, IImageExchangeClient>();


        public void Connect(string deviceIdentifier)
        {
           var connection = OperationContext.Current.GetCallbackChannel<IImageExchangeClient>();
            if (!_connectedDevices.ContainsKey(deviceIdentifier))
            {
                _connectedDevices.Add(deviceIdentifier, connection);
            }
            else
            {
                _connectedDevices[deviceIdentifier] = connection;
            }

            Console.WriteLine("\nDevice connected: {0}", deviceIdentifier);


        }
}

и, наконец, это мой код UWP, где я пытаюсь вызвать Connect метод

        public async void InitializeImageExchangeClient()
        {

            var endpoint = new EndpointAddress(new Uri("net.tcp://localhost:4322/WcfService/Services/ImageExchangeService/tcp"));
            var InstanceContext = new InstanceContext(new ImageExchangeCallback());

            var client = new ImageExchangeService.ImageExchangeServiceClient(buildBinding(), endpoint);
            var channelFactory = (DuplexChannelFactory<IImageExchangeService>)(client.ChannelFactory);
            var proxy = channelFactory.CreateChannel(InstanceContext);
            await proxy.ConnectAsync(DeviceIdentifier);
}

Я также пробовал другой подход к этому методу, например:

            var client = new ImageExchangeServiceClientBase(InstanceContext, buildBinding(), endpoint);
            await client.OpenAsync();
            await client.ConnectAsync(DeviceIdentifier);

buildBinding() функция выглядит так:

private NetTcpBinding buildBinding()
        {
            var binding = new NetTcpBinding()
            {

                MaxReceivedMessageSize = int.MaxValue,
                MaxBufferPoolSize = int.MaxValue,
                ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas()
                {
                    MaxArrayLength = int.MaxValue,
                    MaxBytesPerRead = int.MaxValue,
                    MaxDepth = int.MaxValue,
                    MaxNameTableCharCount = int.MaxValue,
                    MaxStringContentLength = int.MaxValue
                },
                OpenTimeout = TimeSpan.MaxValue,
                ReceiveTimeout = TimeSpan.MaxValue,


            };
            binding.Security.Mode = SecurityMode.None;
            binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None;
            binding.Security.Message.ClientCredentialType = MessageCredentialType.None;

            return binding;
        }

Фактический результат - метод Connect не запускается, и когда я переключаю точку останова на этом методе, он не срабатывает. Другие недуплексные сервисы работают без проблем. Когда я реализовал этот сервис в приложении WPF, метод вызывается правильно, и все работает нормально, проблема заключается в том, что я пытаюсь реализовать это в архитектуре UWP. Спасибо за помощь заранее.

...