簡體   English   中英

WCF服務與主機應用程序之間如何通信?

[英]How to communicate between WCF service and host application?

我通過本教程創建了WCF服務。 這很好用,這里沒有問題。 現在,我將服務托管在托管應用程序中。 但是同時,我想使用從客戶端到主機應用程序中服務的輸入。

我不需要客戶端和服務之間的雙工通信。 我只需要服務與主機之間的通信即可。

處理此問題的最佳方法是什么?

我設法使用來自這個問題的信息來解決它。 有人指出,服務類也可以傳遞給主機。 然后,就像添加事件偵聽器一樣簡單,該事件偵聽器響應來自Service的事件。

有一個可用的框架和教程似乎可以很好地解決Codeplex上的WPF服務主機問題

編輯:更新以說明WPF服務主機模板創建的技術。

WPF服務主機是Visual Studio的模板,用於創建框架應用程序和測試客戶端。 我將在這里描述相關的部分。

這是骨架項目的樣子:

骨架項目

ClientServiceHost.cs

using System;
using System.ServiceModel;

namespace WPFServiceHost1.Service
{
    public class ClientServiceHost : IDisposable
    {
        private bool _Initalized;

        private ServiceHost _InnerServiceHost;
        private MainWindow _MainWindow;

        public ClientServiceHost(MainWindow mainWindow)
        {
            _MainWindow = mainWindow;
            InitializeServiceHost();
        }

        private void InitializeServiceHost()
        {
            try
            {
                ClientService clientService = new ClientService(_MainWindow);
                _InnerServiceHost = new ServiceHost(clientService);

                _InnerServiceHost.Opened += new EventHandler(_InnerServiceHost_Opened);
                _InnerServiceHost.Faulted += new EventHandler(_InnerServiceHost_Faulted);
                _InnerServiceHost.Open();
            }
            catch (Exception ex)
            {
                throw new Exception("Unable to initialize ClientServiceHost", ex);
            }
        }

        void _InnerServiceHost_Opened(object sender, EventArgs e)
        {
            _Initalized = true;
        }

        void _InnerServiceHost_Faulted(object sender, EventArgs e)
        {
            this._InnerServiceHost.Abort();

            if (_Initalized)
            {
                _Initalized = false;
                InitializeServiceHost();
            }
        }

        #region IDisposable Members

        public void Dispose()
        {
            try
            {
                _InnerServiceHost.Opened -= _InnerServiceHost_Opened;
                _InnerServiceHost.Faulted -= _InnerServiceHost_Faulted;
                _InnerServiceHost.Close();
            }
            catch
            {
                try { _InnerServiceHost.Abort(); }
                catch { }
            }
        }
        #endregion
    }
}

MainWindow.xaml

<Window x:Class="WPFServiceHost1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="WPFServiceHost1" Height="344" Width="343" Closing="Window_Closing">
    <Grid>
        <Label Height="28" Margin="12,12,0,0" Name="label1" VerticalAlignment="Top" HorizontalAlignment="Left" Width="119">Messages received:</Label>
        <ListBox Margin="21,38,26,21" Name="listBox1" />
    </Grid>
</Window>

MainWindow.xaml.cs

using System.Threading;
using WPFServiceHost1.Service;

namespace WPFServiceHost1
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public SynchronizationContext _SyncContext = SynchronizationContext.Current;
        private ClientServiceHost _ClientServiceHost;

        public MainWindow()
        {
            InitializeComponent();
            _ClientServiceHost = new ClientServiceHost(this);
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            _ClientServiceHost.Dispose();
        }
    }
}

IClientService.cs

using System.ServiceModel;

namespace WPFServiceHost1.Service
{
    [ServiceContract(Namespace = "urn:WPFServiceHost")]
    public interface IClientService
    {
        [OperationContract]
        void ClientNotification(string message);
    }
}

ClientService.cs

using System;
using System.ServiceModel;

namespace WPFServiceHost1.Service
{
    [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single, InstanceContextMode = InstanceContextMode.Single, UseSynchronizationContext = false)]
    public class ClientService : IClientService
    {
        private MainWindow _MainWindow;

        public ClientService(MainWindow window)
        {
            _MainWindow = window;
        }

        #region IClientService Members
        public void ClientNotification(string message)
        {
            try
            {
                _MainWindow._SyncContext.Send(state =>
                {
                    _MainWindow.listBox1.Items.Add(message);
                }, null);
            }
            catch (Exception ex)
            {
                throw new FaultException(ex.Message);
            }
        }
        #endregion
    }
}

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.serviceModel>
        <behaviors>
            <serviceBehaviors>
                <behavior name="ClientServiceBehavior">
                    <serviceDebug includeExceptionDetailInFaults="false" />
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <services>
            <service behaviorConfiguration="ClientServiceBehavior"
                name="WPFServiceHost1.Service.ClientService">
                <endpoint address="ClientService" binding="basicHttpBinding" contract="WPFServiceHost1.Service.IClientService"/>
                <host>
                    <baseAddresses>
                        <add baseAddress="http://localhost:8010" />
                    </baseAddresses>
                </host>
            </service>
        </services>
    </system.serviceModel>
</configuration>

還有TestClient,Program.cs:

using System;
using System.ServiceModel;
using System.Threading;

namespace TestClient
{
    class Program
    {
        static void Main(string[] args)
        {
            IClientService proxy = null;

            try
            {
                proxy = ChannelFactory<IClientService>.CreateChannel(new BasicHttpBinding(), new EndpointAddress("http://localhost:8010/ClientService"));
                Console.WriteLine("Press <Enter> when ClientService is running.");
                Console.ReadLine();
                Console.WriteLine();

                Console.WriteLine("Sending a single message to ClientService");
                proxy.ClientNotification("Hello from TestClient");

                Console.WriteLine();

                Console.Write("Enter a valid number to load test ClientService: ");
                string result = Console.ReadLine();
                int testCount = Convert.ToInt32(result);
                int counter = 0;
                object counterLock = new object();

                while (true)
                {
                    lock (counterLock)
                    {
                        Thread t = new Thread(() => proxy.ClientNotification(string.Format("Load test from TestClient: {0}", ++counter)));
                        t.Start();
                    }

                    if (counter == testCount)
                        break;
                }

                Console.ReadLine();
            }
            finally
            {
                ICommunicationObject co = proxy as ICommunicationObject;
                try
                {
                    co.Close();
                }
                catch { co.Abort(); }
            }

            Console.ReadLine();
        }
    }
}

就像線程之間的通信一樣。 您需要一些具有適當鎖定/同步的共享變量。 您的主機應用程序將寫入此變量,並且您的服務將能夠從該變量讀取。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM