CoreWCF service push message actively via pub and subscribe,de facto via callback

get-project -all |Install-Package corewcf.nettcp
get-project -all |Install-Package corewcf.primitives
get-project -all |Install-Package Microsoft.Extensions.Hosting
get-project -all |Install-Package System.ServiceModel.NetTcp

 

1.Start a ConsoleApplication as WCFService,installed above packages

2.

using CoreWCF;
using System.Collections.Concurrent;
using Microsoft.AspNetCore.Builder;
using CoreWCF.Configuration;
namespace CoreWCFService
{
    internal class Program
    {
        static long id = 0;
        static async Task Main(string[] args)
        {
            await WCFServicePushDemoAsync(args);
            Console.Read();
        }

        static async Task WCFServicePushDemoAsync(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);
            builder.Services.AddServiceModelServices();

            builder.WebHost.UseNetTcp(8000);

            var app = builder.Build();

            app.UseServiceModel(serviceBuilder =>
            {
                var binding = new NetTcpBinding();
                binding.Security.Mode = SecurityMode.None;
                binding.MaxReceivedMessageSize = int.MaxValue;

                serviceBuilder.AddService<PushService>()
                .AddServiceEndpoint<PushService, IPushService>(binding, "/PushService");
            });

            var timer = new System.Timers.Timer(2000);
            timer.Elapsed += (s, e) =>
            {
                var msg = $"{DateTime.Now},CoreWCFService push:{DateTime.Now}_Id_{Interlocked.Add(ref id, 1)}_{Guid.NewGuid():N}";
                PushService.BroadcastMsg(msg);
                Console.WriteLine($"In CoreWCFService,pushed:\n{msg}\n\n");
            };

            timer.Start();

            Console.WriteLine($"In CoreWCF NetTcp Servive started :net.tcp://127.0.0.1:8000/PushService");

            try
            {
                Console.WriteLine("Listening net.tcp://127.0.0.1:8000/PushService");
                await app.RunAsync();
            }
            finally
            {
                timer.Stop();
                timer.Dispose();
            }
        }
    }

    public interface IMessageCallback
    {
        [OperationContract(IsOneWay = true)]
        void OnPushMessage(string msg);
    }

    [ServiceContract(CallbackContract = typeof(IMessageCallback))]
    public interface IPushService
    {
        [OperationContract]
        void Subscribe();

        [OperationContract]
        void UnSubscribe();
    }


    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession, ConcurrencyMode = ConcurrencyMode.Multiple)]
    public class PushService : IPushService
    {
        private static readonly ConcurrentDictionary<IMessageCallback, byte> _clients = new ConcurrentDictionary<IMessageCallback, byte>();
        private readonly IMessageCallback _callback;

        public PushService()
        {
            _callback = OperationContext.Current.GetCallbackChannel<IMessageCallback>();
        }

        public void Subscribe()
        {
            _clients.TryAdd(_callback, 0);
            Console.WriteLine($"In WCF Service,{DateTime.Now},client subscribe successfully!");
        }

        public void UnSubscribe()
        {
            _clients.TryRemove(_callback, out _);
            Console.WriteLine($"In WCFService,{DateTime.Now},Client unsubscribed subscription");

        }

        public static void BroadcastMsg(string msg)
        {
            foreach (var client in _clients.Keys)
            {
                try
                {
                    client.OnPushMessage(msg);
                }
                catch (Exception)
                {
                    _clients.TryRemove(client, out _);
                }
            }
        }
    }
}

3.WCF CSProj

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
  
    <ItemGroup>
    <FrameworkReference Include="Microsoft.AspNetCore.App" />
  </ItemGroup>
  
    <ItemGroup>
    <PackageReference Include="corewcf.nettcp" Version="1.9.1" />
    <PackageReference Include="corewcf.primitives" Version="1.9.1" />
    <PackageReference Include="Microsoft.Extensions.Hosting" Version="11.0.0" />
  </ItemGroup>


</Project>

 

image

 

 

4.Start another ConsoleApplication as consumer

using System.ServiceModel;namespace CoreWCFConsumer
{
    internal class Program
    {
        static void Main(string[] args)
        {
            SubWCFService();
            Console.ReadLine();
        }

        static void SubWCFService()
        {
            var callbackObj = new ClientCallback();
            var instanceCtx = new InstanceContext(callbackObj);

            var binding = new NetTcpBinding(SecurityMode.None)
            {
                MaxReceivedMessageSize = int.MaxValue,
                // Push/duplex over net.tcp needs a reasonable timeout + reliable session off
                OpenTimeout = TimeSpan.FromSeconds(30),
                SendTimeout = TimeSpan.FromMinutes(10),
                ReceiveTimeout = TimeSpan.FromMinutes(10),
                CloseTimeout = TimeSpan.FromSeconds(30)
            };
            // For a long-lived callback channel, disable reliable session:
            binding.ReliableSession.Enabled = false;

            var address = new System.ServiceModel.EndpointAddress("net.tcp://127.0.0.1:8000/PushService");

            var factory = new DuplexChannelFactory<IPushService>(
                instanceCtx,
                binding,
                address);

            var proxy = factory.CreateChannel();
            proxy.Subscribe();

            Console.WriteLine("Subscribed. Press Enter to exit...");
            Console.ReadLine();

            ((IClientChannel)proxy).Close();
            factory.Close();
        }

    }

    public interface IMessageCallback
    {
        [OperationContract(IsOneWay = true)]
        void OnPushMessage(string msg);
    }

    [ServiceContract(CallbackContract = typeof(IMessageCallback))]
    public interface IPushService
    {
        [OperationContract]
        void Subscribe();

        [OperationContract]
        void UnSubscribe();
    }

    public class ClientCallback : IMessageCallback
    {
        public void OnPushMessage(string msg)
        {
            Console.WriteLine($"In CoreWCFConsumer,{DateTime.Now},received:{msg}");
            Console.WriteLine("\n\n\n\n\n");
        }
    }
}

 

5.ConsumerClient.csproj

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
  
    <ItemGroup>
    <FrameworkReference Include="Microsoft.AspNetCore.App" />
  </ItemGroup>
  
    <ItemGroup>
    <PackageReference Include="corewcf.nettcp" Version="1.9.1" />
    <PackageReference Include="corewcf.primitives" Version="1.9.1" />
    <PackageReference Include="Microsoft.Extensions.Hosting" Version="11.0.0" />
  </ItemGroup>


</Project>

 

image

 

 

6.Start WCF service,then start WCF consumer.

 

image

 

 

 

image

 

 

 

 

 

 

image

 

 

 

image

 

posted @ 2026-11-19 21:28  FredGrit  阅读(10)  评论(0)    收藏  举报