Tag Archives: Akka .NET

P2P Chat with Akka .NET using Akka.Remote

In this article, we’re going to develop a Peer-to-Peer (P2P) Chat application. This means that unlike the official Chat example, which has distinct Client and Server roles, each running instance of the application is exactly the same, except for configuration. The Akka.Remoting documentation explains that Akka.Remote is better suited for P2P applications rather than client/server.

In my typical style, I am keeping this example super simple so that we can focus on learning to message remote actors using Akka.Remote. I am still learning to use Akka .NET, so do not consider this article as an example of best practices.

The source code for this article is available at the Gigi Labs BitBucket repository.

NuGet Packages

Aside from the Akka package needed by all Akka .NET applications, we will also need the Akka.Remote package if we want to send messages to remote actors.

Install-Package Akka
Install-Package Akka.Remote

Configuration

If you’re going to use HOCON configuration from your App.config file, you need to declare a configSection for it:

  <configSections>
    <section name="akka" type="Akka.Configuration.Hocon.AkkaConfigurationSection, Akka" />
  </configSections>

You then set up Akka.Remote as follows:

  <akka>
    <hocon>
      <![CDATA[
        
        akka
        {
            actor
            {
                provider = "Akka.Remote.RemoteActorRefProvider, Akka.Remote"
            }

            remote 
            {
                helios.tcp
                {
                    port = 5248
                    hostname = localhost
                }
            }
        }
      
      ]]>
    </hocon>
  </akka>

The provider part is always the same, so you can just copy it. The helios.tcp section specifies the TCP endpoint on which the ActorSystem will listen for incoming connections, in this case localhost:5248.

For this particular example only, I am also going to include some AppSettings that we need in order to differentiate between different running instances of the chat application:

  <appSettings>
    <add key="actorSystemName" value="ChatPeer1" />
    <add key="remoteActorAddress" value="akka.tcp://ChatPeer2@localhost:5249/user/ChatActor" />
  </appSettings>

The actorSystemName setting has two purposes here.

  1. We will use it to display a different console title, so that we can distinguish between different running instances of the same application.
  2. We will actually give a different name to each running ActorSystem.

The remoteActorAddress setting, on the other hand, tells us the location of the remote chat actor. In this way, two running instances of the application will be able to connect and send messages to each other:

akka.remote-p2p-design

Typically you could just have one instance connect to the other, and the second communicates to the first via Sender.Tell() as in the Sending Messages to Remote Actors documentation. I arbitrarily chose not to do this to keep the application instances as symmetrical as possible (which is a typical trait of P2P applications).

Chat Application

Without further ado, here is the full code for the P2P Chat application within a console application’s Main() method:

            string actorSystemName = ConfigurationManager.AppSettings["actorSystemName"];
            Console.Title = actorSystemName;

            try
            {
                using (var actorSystem = ActorSystem.Create(actorSystemName))
                {
                    var localChatActor = actorSystem.ActorOf(Props.Create<ChatActor>(), "ChatActor");

                    string remoteActorAddress = ConfigurationManager.AppSettings["remoteActorAddress"];
                    var remoteChatActor = actorSystem.ActorSelection(remoteActorAddress);

                    if (remoteChatActor != null)
                    {
                        string line = string.Empty;
                        while (line != null)
                        {
                            line = Console.ReadLine();
                            remoteChatActor.Tell(line);
                        }
                    }
                    else
                    {
                        Console.WriteLine("Could not get remote actor ref");
                        Console.ReadLine();
                    }
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex);
            }

From all this code, there are only two parts that are important to note. First, we are creating a local chat actor. This is what the remote actor will connect to in order to talk to the current instance of the application. It does this using the highlighted portion of code. It is simply getting a reference to the remote actor (using the address we specified in configuration) and locating it via an ActorSelection.

The ChatActor doesn’t do anything special. It simply writes whatever message it receives to the console:

    public class ChatActor : TypedActor, IHandle<string>
    {
        public ChatActor()
        {
            
        }

        public void Handle(string message)
        {
            using (var colour = new ScopedConsoleColour(ConsoleColor.White))
                Console.WriteLine(message);
        }
    }

It’s using the ScopedConsoleColour utility class from my Scope Bound Resource Management in C# article just to make received text look different from the text you type in:

    public class ScopedConsoleColour : IDisposable
    {
        private ConsoleColor oldColour;

        public ScopedConsoleColour(ConsoleColor newColour)
        {
            this.oldColour = Console.ForegroundColor;

            Console.ForegroundColor = newColour;
        }

        public void Dispose()
        {
            Console.ForegroundColor = this.oldColour;
        }
    }

Running the Application

We want to run two instances of the same application, but using different configuration. This not only allows us to recognise which is which, but also ensures that each instance can connect to the other at the right endpoint. The applications could run on the same machine or on different machines altogether.

The first instance will use configuration as shown earlier:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="akka" type="Akka.Configuration.Hocon.AkkaConfigurationSection, Akka" />
  </configSections>
    
  <startup> 
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  </startup>

  <appSettings>
    <add key="actorSystemName" value="ChatPeer1" />
    <add key="remoteActorAddress" value="akka.tcp://ChatPeer2@localhost:5249/user/ChatActor" />
  </appSettings>
    
  <akka>
    <hocon>
      <![CDATA[
        
        akka
        {
            actor
            {
                provider = "Akka.Remote.RemoteActorRefProvider, Akka.Remote"
            }

            remote 
            {
                helios.tcp
                {
                    port = 5248
                    hostname = localhost
                }
            }
        }
      
      ]]>
    </hocon>
  </akka>
</configuration>

The second will use opposite configuration:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="akka" type="Akka.Configuration.Hocon.AkkaConfigurationSection, Akka" />
  </configSections>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  </startup>

  <appSettings>
    <add key="actorSystemName" value="ChatPeer2" />
    <add key="remoteActorAddress" value="akka.tcp://ChatPeer1@localhost:5248/user/ChatActor" />
  </appSettings>

  <akka>
    <hocon>
      <![CDATA[
        
        akka
        {
            actor
            {
                provider = "Akka.Remote.RemoteActorRefProvider, Akka.Remote"
            }

            remote 
            {
                helios.tcp
                {
                    port = 5249
                    hostname = localhost
                }
            }
        }
      
      ]]>
    </hocon>
  </akka>
</configuration>

When we run the two instances, each with its own configuration, we can actually have them send messages to each other:

akka.remote-chat-demo

Disconnecting

If we close the second instance, you’ll see that this does not go unnoticed by the first instance that is still running:

akka.remote-p2p-disconnect

However, if we run the second instance again, you can see that it recovers, and from then it’s business as usual:

akka.remote-p2p-reconnect

Further Reading

This article was really just a proof of concept to show how Akka.Remote works in practice. You might also want to check out:

  1. Akka.Remote Overview (official documentation)
  2. Sending Messages to Remote Actors (official documentation)
  3. Location Transparency (official documentation)
  4. Chat Example (official examples)

Dependency Injection in Akka .NET

If you’ve read yesterday’s article, “Actor Logging with Akka .NET“, you’ll know that Akka .NET is pretty flexible in terms of the logging frameworks it supports. It uses an adapter so you can pretty much plug in whatever logging framework you prefer.

Akka .NET’s approach to dependency injection is no different. Instead of imposing a particular framework or using its own, Akka .NET lets you plug in a selection of popular third party dependency injection frameworks and use them via a common interface.

The source code for this article is available at the Gigi Labs BitBucket repository.

Example Application

To show how to work with dependency injection (DI), we’ll set up a simple example. No need to get fancy here. All we need is a way to create a parent actor (directly from the ActorSystem) and child actor (from the parent actor). These should have a dependency injected in the constructor.

Here’s the interface for our dependency. I told you, nothing fancy.

    public interface ILazyAss
    {
        void DoNothing();
    }

Here’s the concrete implementation that implements this interface.

    public class SheriffBlake : ILazyAss
    {
        public void DoNothing()
        {
            
        }
    }

Before we start setting up our ActorSystem, we need to install the Akka NuGet package:

Install-Package Akka

Now, we need our actors. We don’t really care what they do, as long as they take the ILazyAss dependency so that we can show later that the DI works. Also, the parent actor creates a child actor – currently not using DI.

    public class ParentActor : ReceiveActor
    {
        public ParentActor(ILazyAss lazyAss)
        {
            Console.WriteLine("Parent Actor created!");

            var childActor = Context.ActorOf(
                Props.Create<ChildActor>(lazyAss), "ChildActor");
        }
    }

    public class ChildActor : ReceiveActor
    {
        public ChildActor(ILazyAss lazyAss)
        {
            Console.WriteLine("Child Actor created!");
        }
    }

We can now set up our ActorSystem:

        static void Main(string[] args)
        {
            using (var actorSystem = ActorSystem.Create("MyActorSystem"))
            {
                var lazyAss = new SheriffBlake();
                var actor = actorSystem.ActorOf(
                    Props.Create<ParentActor>(lazyAss), "ParentActor");

                Console.WriteLine("Press ENTER to exit...");
                Console.ReadLine();
            }
        }

Let us now run the code as is and see that it works:

akkanetdi-nodioutput

Setting up DI with Ninject

Like with logging, DI in Akka .NET involves installing the adapter NuGet package for the framework you want, and then configuring it as needed. I’m going to show how to do this with Ninject, but this is an arbitrary choice. Consult the Akka .NET Dependency Injection documentation for more information about how to set up other dependency injection frameworks. Packages for other frameworks not listed there also exist in NuGet.

akkanetdi-diadapters

So first, install the package you need:

Install-Package Akka.DI.Ninject

Next, we set up our IoC container, configure the dependencies we need to resolve, and set it up to work with the ActorSystem:

        static void Main(string[] args)
        {
            var container = new StandardKernel();
            container.Bind<ILazyAss>().To<SheriffBlake>();

            using (var actorSystem = ActorSystem.Create("MyActorSystem"))
            {
                var resolver = new NinjectDependencyResolver(container, actorSystem);

                var lazyAss = new SheriffBlake();
                var actor = actorSystem.ActorOf(
                    Props.Create<ParentActor>(lazyAss), "ParentActor");

                Console.WriteLine("Press ENTER to exit...");
                Console.ReadLine();
            }
        }

We now need to stop directly creating the dependency, and rely on the DI framework instead.

The catch to do this is that you need this funky DI() extension method, for which you need the following using statement:

using Akka.DI.Core;

This DI() extension method can be used from actor systems as well as actor contexts to create actors. Let’s change our actor system to use this, and get rid of the direct creation of our lazy sheriff:

        static void Main(string[] args)
        {
            var container = new StandardKernel();
            container.Bind<ILazyAss>().To<SheriffBlake>();

            using (var actorSystem = ActorSystem.Create("MyActorSystem"))
            {
                var resolver = new NinjectDependencyResolver(container, actorSystem);

                var actor = actorSystem.ActorOf(
                    actorSystem.DI().Props<ParentActor>(), "ParentActor");

                Console.WriteLine("Press ENTER to exit...");
                Console.ReadLine();
            }
        }

Similarly, we can rewire our ParentActor to create the ChildActor via DI (remember to add the using to get access to the DI() extension method):

    public class ParentActor : ReceiveActor
    {
        public ParentActor(ILazyAss lazyAss)
        {
            Console.WriteLine("Parent Actor created!");

            var childActorProps = Context.DI().Props<ChildActor>();
            var childActor = Context.ActorOf(childActorProps, "ChildActor");
        }
    }

And voilà:

akkanetdi-dioutput

Actor Logging with Akka .NET

In this article, we’re going to see how we can work with logging in Akka .NET. There is a logging adapter which allows one to work with various different logging providers (e.g. NLog), and it is very easy to use from within actors.

The source code for this article is available at the Gigi Labs BitBucket repository.

Example Application

Before we get to the details of how to use logging in Akka .NET, let’s create a very simple application. The first thing we need to do is install the Akka package:

Install-Package Akka

To work with basic Akka components, we need the following using:

using Akka.Actor;

We can now create a simple actor. This actor will just output whatever message (string) it receives:

    public class LoggingActor : ReceiveActor
    {
        public LoggingActor()
        {
            this.Receive<string>(s => Console.WriteLine(s));
        }
    }

Finally, we create our ActorSystem in Main() and send a message to the actor:

        static void Main(string[] args)
        {
            Console.Title = "Akka .NET Logging";

            using (var actorSystem = ActorSystem.Create("MyActorSystem"))
            {
                Console.WriteLine("ActorSystem created!");

                var actor = actorSystem.ActorOf(Props.Create<LoggingActor>(), "loggingActor");

                actor.Tell("Hello!");

                Console.WriteLine("Press ENTER to exit...");
                Console.ReadLine();
            }
        }

If we run this, we get the following output:

akkanetlogging-initialoutput

You can see that some of the output came from the Console.WriteLine()s we have in Main(); while the “Hello!” message came from the actor. But there is also a warning that is not coming from anywhere within our code.

StandardOutLogger

We can adjust our actor’s code to use a logger instead of writing directly to the console. The actor doesn’t care what kind of logger it is; this detail is entirely configurable. By default, it will use the StandardOutLogger which writes to the console. But we can use something else (e.g. NLog or Serilog) and the code would be completely unchanged.

    public class LoggingActor : ReceiveActor
    {
        private readonly ILoggingAdapter logger = Logging.GetLogger(Context);

        public LoggingActor()
        {
            this.Receive<string>(s => logger.Info(s));
        }
    }

If we run this, the “Hello!” message still gets written to the console, but it is now part of a longer formatted log message:

akkanetlogging-standardoutlogger

LogLevel

Just about all logging frameworks have a concept of log level. Typically these consist of at least Debug, Info, Warning and Error (some even have a Fatal level). You tell the logging framework what is the minimum level you’re interested in. So if your minimum level is Warning, the logging framework omits Debug and Info messages.

In Akka .NET, you can configure the minimum log level you’re interested in as part of the HOCON configuration within your App.config as follows:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <configSections>
    <section name="akka" type="Akka.Configuration.Hocon.AkkaConfigurationSection, Akka" />
  </configSections>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  </startup>

  <akka>
    <hocon>
      <![CDATA[ akka { loglevel = DEBUG } ]]>
    </hocon>
  </akka>

</configuration>

If we set loglevel to INFO, we get exactly the same as before. But now that we’ve set it to DEBUG, we actually get some additional logging from within Akka .NET:

akkanetlogging-debugoutput

Note: the screenshot actually contradicts what I was saying earlier about the StandardOutLogger. It actually seems to be replacing StandardOutLogger with this DefaultLogger. Presumably DefaultLogger uses StandardOutLogger underneath.

Automatic Logging

Akka .NET provides certain logging mechanisms out of the box. One of these is logging received messages (so we don’t even need to do that in code). You can turn on these mechanisms in the HOCON configuration as follows:

  <akka>
    <hocon>
      <![CDATA[
        akka
        {
          loglevel = DEBUG
          
          actor
          {
            debug
            {
              receive = on      # log any received message
              autoreceive = on  # log automatically received messages, e.g. PoisonPill
              lifecycle = on    # log actor lifecycle changes
              event-stream = on # log subscription changes for Akka.NET event stream
              unhandled = on    # log unhandled messages sent to actors
            }
          }
        }
      ]]>
    </hocon>
  </akka>

Now, to actually log received messages, you also need to make your actor implement the empty ILogReceive interface as per this StackOverflow question:

    public class LoggingActor : ReceiveActor, ILogReceive

If you run the application now, you’ll see that a lot more messages are being logged, including another entry for the “Hello!” message:

akkanetlogging-automaticlogging

Tip: ideally make sure the loglevel HOCON setting and the node under actor in HOCON (in this case debug) are in sync. If you set loglevel to INFO now, all the automatic logging will stop writing.

Integrating NLog

The logging adapter is particularly useful because you can swap out logging frameworks without having to touch the code. We are currently using the StandardOutLogger (or DefaultLogger?), but with some simple configuration, we can use NLog or some other provider instead.

The Akka .NET Logging documentation page shows the currently supported logging frameworks. Typically, you install a NuGet package for the framework you want, and set up its own configuration. I’m going to show you how to do this with NLog, but it’s an arbitrary choice, and the steps are similar for other logging frameworks.

1. Install the relevant NuGet package:

Install-Package Akka.Logger.NLog

2. Add an NLog.config to the project and configure it as you like:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <targets>
    <target name="file" xsi:type="File" fileName="test.log" />
  </targets>
  
  <rules>
    <logger name="*" minlevel="Info" writeTo="file" />
  </rules>
  
</nlog>

3. Right click NLog.config, Properties, then set to Copy always or Copy if newer:

akkanetlogging-copyalways

4. Update your HOCON to use the relevant logger:

  <akka>
    <hocon>
      <![CDATA[
        akka
        {
          loglevel = DEBUG
          loggers = ["Akka.Logger.NLog.NLogLogger, Akka.Logger.NLog"]
          
          actor
          {
            debug
            {
              receive = on      # log any received message
              autoreceive = on  # log automatically received messages, e.g. PoisonPill
              lifecycle = on    # log actor lifecycle changes
              event-stream = on # log subscription changes for Akka.NET event stream
              unhandled = on    # log unhandled messages sent to actors
            }
          }
        }
      ]]>
    </hocon>
  </akka>

Let’s run it now:

akkanetlogging-nlogoutput

You can see that the console output is now limited to what we’re writing in Main(), while the rest has gone into a file called test.log. Since our minlevel is Info, we’re not getting the automatic logging which is configured for the debug log level.