Giter VIP home page Giter VIP logo

tinyipc's Introduction

TinyIpc

NuGet Build

.NET inter process broadcast message bus.

Intended for quick broadcast messaging in Windows desktop applications, it just works.

Quick introduction

  • Designed to be serverless
  • Clients may drop in and out at any time
  • Messages expire after a specified timeout, default 500 milliseconds
  • The log is kept small for performance, default max log size is 1 MB
  • Reads are queued and should be received in the same order as they were published

Benefits and drawbacks

It's easy to use and there is no complicated setup. It is suited for small messages, so big messages probably need some other transport mechanism. With high enough throughput messages may be lost if receivers are not able to get a read lock before the message timeout is reached.

Performance

Every publish operation reads and writes the entire contents of a shared memory mapped file and every read operation which is triggered by writes also reads the entire file so if performance is important then batch publish several messages at once to reduce the amount of reads and writes.

OS Support

Unfortunately TinyIpc only works on Windows because the named primitives that are core to this entire solution only works on Windows and throws PlatformNotSupportedException on other operating systems by design.

See dotnet/runtime#4370 for more information.

Compared to other solutions

TinyIPC IpcChannel Named Pipes
Broadcasting to all listeners (except self)
No master process
Insensitive to process privilege level
Entirely in memory

Simple example

One message bus listening to the other. Check ConsoleApp for a sample application.

using var messagebus1 = new TinyMessageBus("ExampleChannel");
using var messagebus2 = new TinyMessageBus("ExampleChannel");

messagebus2.MessageReceived +=
	(sender, e) => Console.WriteLine(Encoding.UTF8.GetString(e.Message));

while (true)
{
	var message = Console.ReadLine();
	await messagebus1.PublishAsync(Encoding.UTF8.GetBytes(message));
}

Example using generic hosting

Equivalent example to the above using generic hosting. Check GenericHost for a sample application.

// Add service to IServiceCollection
services.AddTinyIpc(options =>
{
	options.Name = "ExampleChannel";
});

// Later use ITinyIpcFactory to create instances
using var tinyIpcInstance1 = tinyIpcFactory.CreateInstance();
using var tinyIpcInstance2 = tinyIpcFactory.CreateInstance();

tinyIpcInstance2.MessageBus.MessageReceived +=
	(sender, e) => Console.WriteLine(Encoding.UTF8.GetString(e.Message));

while (true)
{
	var message = Console.ReadLine();
	await tinyIpcInstance1.MessageBus.PublishAsync(Encoding.UTF8.GetBytes(message));
}

tinyipc's People

Contributors

davidzidar avatar githubpang avatar weazl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tinyipc's Issues

Global Memory Map Issue

I am using this Library for a very long time now, and the thing that is missing imo is the ability to create globally mapped files. So i could communicate between Services and Processes. This could be acomplished by maybe adding a flag, that prepends the "Global" prefix to all Handles.

Compiling in NET5 -> BinaryFormatter serialization methods are obsolete and prohibited

File SerializationExtensions.cs uses old methods and you get warnings if compiling in NET5.

Solution:

using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace SingleInstanceCore
{
	//For inline serializing and deserializing
	internal static class SerializationExtensions
	{
		internal static byte[] Serialize<T>(this T obj)
		{
			return Encoding.UTF8.GetBytes(JsonSerializer.Serialize(obj, GetJsonSerializerOptions()));
		}

		internal static T Deserialize<T>(this byte[] data)
		{
			return JsonSerializer.Deserialize<T>(data, GetJsonSerializerOptions());
		}

		private static JsonSerializerOptions GetJsonSerializerOptions()
		{
			return new JsonSerializerOptions()
			{
				PropertyNamingPolicy = null,
				WriteIndented = true,
				AllowTrailingCommas = true,
				DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
			};
		}
	}
}

Randomly getting this

System.TimeoutException: Gave up waiting for read lock
at TinyIpc.Synchronization.TinyReadWriteLock.AcquireReadLock()
at TinyIpc.IO.TinyMemoryMappedFile.Read()
at TinyIpc.Messaging.TinyMessageBus..ctor(ITinyMemoryMappedFile memoryMappedFile, Boolean disposeFile, TimeSpan minMessageAge)

when calling the constructor, presumably to create the memory mapped file

any idea how to fix. The only way it goes away is if i restart my machine

Running as a Service

I've been working on a service that runs in session 0 on windows 7+ machines, and launches a GUI in the user's session that allows me to do certain things with System access.

However, I can't get the processes to communicate with TinyIpc. If I run my service as a normal program, it works without any changes, but as soon as it's running as System (in session 0) it fails to receive messages from TinyIpc.

Client:

TinyMessageBus ipc = new TinyMessageBus("test");
ipc.PublishAsync(CreateHelloPacket());

Service:

ipc = new TinyMessageBus("test");
ipc.MessageReceived +=
            (sender, e) => OnMessage(e.Message);

private void OnMessage(byte[] message)
    {
      //...
    }

Any ideas on how to get them to communicate together?

Sample not working

Hi David,
after building your TinyIPC Project without errors and warnings, I run your sample project.... but it did not work as expected... sending seems to work (MessageSent property is increasing for each sent message), but the sample did not receive anything... Can you help me out?
Cheers,
Micha

Named Semaphore not supported on Unix platforms

This is the issue documenting the problem with a lot of the named primitives:
https://github.com/dotnet/coreclr/issues/1237
Basically I don't think this will work under any platforms other than Windows.

I put together a version of the library without the semaphores to control the maximum number of readers/clients but I have only had a very cursory read through the code base so I don't know if that's a terrible idea or not?

Receiving messages too slowly

If the message content is long, the receiving of the message will be very slow, and the interval can even reach 2-3 seconds.
Any good suggestions?
Version is 3.11

Documentation about security

Hello,

This library looks practical for small needs. But what about memory mapped file access control? I am not sure what are the defaults when doing CreateOrOpen without specific MemoryMappedFileSecurity.

Could you explain/document who can listen and send messages on the channel? For instance if running as a Windows service.

Thanks.

Latest version does not work at all

Installed latest version and i cant even get the constructor to work anymore. reverted to previous version for the time being

public static void Initialize()
        {
            try
            {
                bus  = new TinyIpc.Messaging.TinyMessageBus(MessageBusName);
                bus.MessageReceived += Bus_MessageReceived;
            }
            catch (Exception ex)
            {
               
            }
        }

above code throws the following exception

Description: The process was terminated due to an unhandled exception.
Exception Info: System.IO.FileLoadException
at Hscm.IPC.ClientManager.Initialize()
at Hscm.UI.MainWindow.InitializeCore()
at Hscm.UI.MainWindow.Initialize()
at System.Windows.EventRoute.InvokeHandlersImpl(System.Object, System.Windows.RoutedEventArgs, Boolean)
at System.Windows.UIElement.RaiseEventImpl(System.Windows.DependencyObject, System.Windows.RoutedEventArgs)
at System.Windows.BroadcastEventHelper.BroadcastEvent(System.Windows.DependencyObject, System.Windows.RoutedEvent)
at System.Windows.BroadcastEventHelper.BroadcastLoadedEvent(System.Object)
at MS.Internal.LoadedOrUnloadedOperation.DoWork()
at System.Windows.Media.MediaContext.FireLoadedPendingCallbacks()
at System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks()
at System.Windows.Media.MediaContext.RenderMessageHandlerCore(System.Object)
at System.Windows.Media.MediaContext.RenderMessageHandler(System.Object)
at System.Windows.Interop.HwndTarget.OnResize()
at System.Windows.Interop.HwndTarget.HandleMessage(MS.Internal.Interop.WindowMessage, IntPtr, IntPtr)
at System.Windows.Interop.HwndSource.HwndTargetFilterMessage(IntPtr, Int32, IntPtr, IntPtr, Boolean ByRef)
at MS.Win32.HwndWrapper.WndProc(IntPtr, Int32, IntPtr, IntPtr, Boolean ByRef)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(System.Object)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate, System.Object, Int32)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(System.Object, System.Delegate, System.Object, Int32, System.Delegate)
at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(System.Windows.Threading.DispatcherPriority, System.TimeSpan, System.Delegate, System.Object, Int32)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr, Int32, IntPtr, IntPtr)
at MS.Win32.UnsafeNativeMethods.CallWindowProc(IntPtr, IntPtr, Int32, IntPtr, IntPtr)
at MS.Win32.HwndSubclass.DefWndProcWrapper(IntPtr, Int32, IntPtr, IntPtr)
at MS.Win32.UnsafeNativeMethods.CallWindowProc(IntPtr, IntPtr, Int32, IntPtr, IntPtr)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr, Int32, IntPtr, IntPtr)

Not working at all :(

I'm sending ~2500 byte long message in one process once a second on Windows 7.
I'm trying to receive messages in 10 other processes.
The first receiver kind of starts to receive messages, but drops many of them. Other processes are not really receiving anything, sometimes they receive a message, then it all stops receiving, this is terrible :(

Did anyone use this in production or is this some kind of a school project? :(

Any other IPC I can use??

Error when initializing latest

Details

The version of the TinyIpc library included in the project is 4.1.3 (latest).
The .NET framework ver of the project is 4.8.

The code throwing the exception is as follows

bus = new TinyIpc.Messaging.TinyMessageBus("MessageBus");

The exception shown is as follows

Could not load file or assembly 'System.Buffers, Version=4.0.2.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

I have even added this assembly as a reference to the project with the same ver as above, but hasn't fixed.

Let me know if you need any other info to help solve.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.