WCF自主发布/订阅。如何从主机调用发布方法?

时间:2014-04-15 06:34:32

标签: c# wcf

您好我有一个发布/订阅WCF服务,该服务托管在我的应用程序而不是IIS。

以下是服务接口

[ServiceContract(CallbackContract = typeof(IMonitorPublishing))]
public interface IMonitorSubscribing
{
    [OperationContract]
    void Subscribe(int processId);

    [OperationContract]
    void UnScubscribe(int processId);

    [OperationContract]
    void PublishWriteConsole(string Name);
}


[ServiceContract]
public interface IMonitorPublishing
{
    [OperationContract(IsOneWay = true)]
    void WriteConsole(string line);
}

这是Subcription服务

public class MonitorSubscriptionService : IMonitorSubscribing
{
    public delegate void WriteConsoleEventHandler(object sender,    ServiceEventArgs e);
    public static event WriteConsoleEventHandler WriteConsoleEvent;

    IMonitorPublishing publishCallback = null;
    WriteConsoleEventHandler WriteConsoleHandler = null;

    public void Subscribe(int processId)
    {
        publishCallback = OperationContext.Current.GetCallbackChannel<IMonitorPublishing>();
        WriteConsoleHandler = new WriteConsoleEventHandler(PublishWriteConsoleHandler);
        WriteConsoleEvent += WriteConsoleHandler;
        //PublishWriteConsole("Winning")
    }

    public void UnScubscribe(int processId)
    {
        WriteConsoleEvent -= WriteConsoleHandler;
    }

    public void PublishWriteConsole(String text)
    {
        ServiceEventArgs se = new ServiceEventArgs();
        se.Text = text;
        WriteConsoleEvent(this, se);
    }

    public void PublishWriteConsoleHandler(object sernder, ServiceEventArgs se)
    {
        publishCallback.WriteConsole(se.Text);
    }
}

服务主机很好,我可以在我的客户端应用程序中添加服务引用。如果我取消注释&#34; Winning&#34;这会触发客户端的回调方法(一段时间后)。这让我相信订阅和回调都很有效。

我的问题是,在主机应用程序的各个点上,我希望通过PublishWriteConsole回调方法打印到订阅的客户端控制台。如何在主机应用程序中调用此函数我是否需要连接到服务我自己的应用程序正在托管?我很困惑任何帮助都会受到赞赏。

这是相关的App.Config位

<services>
  <service behaviorConfiguration="Monitor.MonitorSubscriptionServiceBehaviour"
           name="Monitor.MonitorSubscriptionService">
    <host>
      <baseAddresses>
        <add baseAddress="net.tcp://localhost:5050/Monitor"/>
      </baseAddresses>
    </host>
    <endpoint address=""  binding="netTcpBinding" bindingConfiguration="" contract="Monitor.IMonitorSubscribing">
      <identity>
        <dns value="localhost"/>
      </identity>
    </endpoint>
    <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange"/>
  </service>
</services>
<behaviors>
  <serviceBehaviors>
    <behavior name="Monitor.MonitorSubscriptionServiceBehaviour">
      <serviceMetadata httpGetEnabled="False"/>      
      <serviceDebug includeExceptionDetailInFaults="False" />
    </behavior>
  </serviceBehaviors>
</behaviors>

0 个答案:

没有答案