WPF 和托管的 WCF 服务之间的通信



我有一个启动 WCF 服务的控制台应用程序和一个小型 WPF 应用程序。每当出于测试目的调用 WCF 服务上的方法时,我都会尝试在 WPF 应用程序中显示一个消息框。我的代码基于这个答案,但同步上下文为空。我该如何解决这个问题?或者有其他/更好的方法来实现这一点吗?

使用 SignalR。这里和这里有很多信息。这篇文章看起来也很好。

对于实际代码,请创建一个 WCF 服务并使用 NuGet 添加对 SignalR 的引用,然后添加一个中心类:

public class ServiceMonitorHub : Hub
{
}

还需要添加一个 Owin 启动类来启动 SignalR 中心:

[assembly: OwinStartup(typeof(YourNamespace.SignalRStartup))]
namespace YourNamespace
{
    public class SignalRStartup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
}

然后,服务处理程序可以获取对此中心的引用,并将消息发送到连接到它的所有客户端:

public class Service1 : IService1
{
    public string GetData(int value)
    {
        // send msg to clients
        var hub = GlobalHost.ConnectionManager.GetHubContext<ServiceMonitorHub>();
        hub.Clients.All.BroadcastMessage();
        return string.Format("You entered: {0}", value);
    }

然后,WPF 客户端连接到此 SignalR 服务器并挂钩处理程序以接收服务处理程序发送的消息,此示例包含一个调用服务的按钮处理程序,以及与 SignalR 中心的连接,以接收退回的消息:

public partial class MainWindow : Window
{
    private HubConnection Connection;
    private IHubProxy HubProxy;
    public MainWindow()
    {
        InitializeComponent();
        Task.Run(ConnectAsync);
    }
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        using (var service = new ServiceReference1.Service1Client())
            service.GetData(1);
    }
    public async Task ConnectAsync()
    {
        try
        {
            this.Connection = new HubConnection("http://localhost:59082/");
            this.HubProxy = this.Connection.CreateHubProxy("ServiceMonitorHub");
            HubProxy.On("BroadcastMessage", () => MessageBox.Show("Received message!"));
            await this.Connection.Start();
        }
        catch (Exception ex)
        {
        }
    }
}

}

请注意,客户端需要 NuGet SignalR.Clients 包(而不仅仅是 SignalR)。

服务还有其他方法

可以调用中心客户端,此链接显示了其他一些方法。

也许你可以试试ClientMessageInspector,每次客户端收到消息时都会调用它的AfterReceiveReprat。

 public class MyClientMessageInspector : IClientMessageInspector
{
          Your message box
    public void AfterReceiveReply(ref Message reply, object correlationState)
    {
       show message in your message box
    }
    public MyClientMessageInspector ( ){
                       }
    public object BeforeSendRequest(ref Message request, IClientChannel channel)
    {
        return null;
    }
}

要注册检查器,需要使用端点行为

  public class MyEndpointBehavior : IEndpointBehavior
{
    public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
    {
    }
    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
        clientRuntime.ClientMessageInspectors.Add( new MyClientMessageInspector();
    }
    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
    {
    }
    public void Validate(ServiceEndpoint endpoint)
    {
    }
}

然后将行为添加到客户端。

 using (ChannelFactory<IService> ChannelFactory = new ChannelFactory<IService>("myservice"))
        {
            ChannelFactory.Endpoint.EndpointBehaviors.Add(new MyEndpointBehavior());
            IService service = ChannelFactory.CreateChannel();
          // call method

        }

最新更新