Skip to content

Instantly share code, notes, and snippets.

@ruxo
Last active February 24, 2024 12:15
Show Gist options
  • Save ruxo/652e9f2e6cfb61efa3a955974e5e2d5e to your computer and use it in GitHub Desktop.
Save ruxo/652e9f2e6cfb61efa3a955974e5e2d5e to your computer and use it in GitHub Desktop.
Simple example of Akka.Net remoting. To run the example, start Ponger first. ``` dotnet fsi ponger.fsx ``` Then start Pinger in another terminal. ``` dotnet fsi pinger.fsx ```
#r "nuget:Akka.Remote"
open System
open Akka.Actor
open Akka.Configuration
type Pinger() =
inherit UntypedActor()
let Context = ActorBase.Context
let pong = ActorBase.Context.ActorSelection("akka.tcp://Ponger@localhost:8000/user/pong")
let echoBack (s: string) =
if s.StartsWith("echo:") then
Console.WriteLine(s)
if s = "echo: quit" then
CoordinatedShutdown.Get(Context.System).Run(CoordinatedShutdown.ClrExitReason.Instance) |> ignore
else
printfn $"Sending: %s{s}"
pong.Tell(s)
override this.OnReceive message =
match message with
| :? string as s -> echoBack s
| _ -> ()
[<Literal>]
let hocon = """
akka {
actor {
provider = remote
}
remote {
dot-netty.tcp {
port = 0 # bound to a dynamic port assigned by the OS
hostname = localhost
}
}
}
"""
let config = ConfigurationFactory.ParseString(hocon)
let system = ActorSystem.Create("Pinger", config)
let pinger = system.ActorOf<Pinger>("ping")
pinger.Tell("Say hello!")
Console.ReadLine() |> ignore
pinger.Tell("quit")
system.WhenTerminated.Wait(TimeSpan.FromSeconds 5)
#r "nuget:Akka.Remote"
open System
open Akka.Actor
open Akka.Configuration
type Ponger() =
inherit UntypedActor()
let Context = ActorBase.Context
let forwardMessage (s: string) =
if s = "start" then
printfn "Let's start!"
else
printfn $"Incoming message: %s{s}"
Context.Sender.Tell($"echo: {s}")
override this.OnReceive message =
match message with
| :? string as s -> forwardMessage s
| _ -> printfn "Pong: unknown message"
[<Literal>]
let hocon = """
akka {
actor {
provider = remote
}
remote {
dot-netty.tcp {
port = 8000
hostname = 127.0.0.1
public-hostname = localhost
}
}
}
"""
let config = ConfigurationFactory.ParseString(hocon)
let system = ActorSystem.Create("Ponger", config)
let ponger = system.ActorOf<Ponger>("pong")
ponger.Tell("start")
printf "Press ENTER to end..."
Console.ReadLine() |> ignore
CoordinatedShutdown.Get(system).Run(CoordinatedShutdown.ClrExitReason.Instance).Wait(TimeSpan.FromSeconds 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment