What steps do I need to take to use WCF Callbacks?

后端 未结 4 755
伪装坚强ぢ
伪装坚强ぢ 2020-12-02 06:46

I am trying to learn WCF. I have a simple client and server application setup and upon pressing a button on the client, it gets an updated value from the server.

4条回答
  •  隐瞒了意图╮
    2020-12-02 07:29

    Here is about the simplest complete example that I can come up with:

    public interface IMyContractCallback
    {
        [OperationContract]
        void OnCallback();
    }
    
    [ServiceContract(CallbackContract = typeof(IMyContractCallback))]
    public interface IMyContract
    {
        [OperationContract]
        void DoSomething();
    }
    
    [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant)]
    public class MyService : IMyContract
    {
        public void DoSomething()
        {
            Console.WriteLine("Hi from server!");
            var callback = OperationContext.Current.GetCallbackChannel();
            callback.OnCallback();
        }
    }
    
    public class MyContractClient : DuplexClientBase
    {
        public MyContractClient(object callbackInstance, Binding binding, EndpointAddress remoteAddress)
            : base(callbackInstance, binding, remoteAddress) { }
    }
    
    public class MyCallbackClient : IMyContractCallback
    {
        public void OnCallback()
        {
            Console.WriteLine("Hi from client!");
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            var uri = new Uri("net.tcp://localhost");
            var binding = new NetTcpBinding();
            var host = new ServiceHost(typeof(MyService), uri);
            host.AddServiceEndpoint(typeof(IMyContract), binding, "");
            host.Open();
    
            var callback = new MyCallbackClient();
            var client = new MyContractClient(callback, binding, new EndpointAddress(uri));
            var proxy = client.ChannelFactory.CreateChannel();
            proxy.DoSomething();
            // Printed in console:
            //  Hi from server!
            //  Hi from client!
    
            client.Close();
            host.Close();
        }
    }
    

    A few namespaces will need to be included in order to run the example:

    using System;
    using System.ServiceModel;
    using System.ServiceModel.Channels;
    

提交回复
热议问题