Skip to content

Instantly share code, notes, and snippets.

@OlegYch
Created March 23, 2012 13:06
Show Gist options
  • Select an option

  • Save OlegYch/2170471 to your computer and use it in GitHub Desktop.

Select an option

Save OlegYch/2170471 to your computer and use it in GitHub Desktop.
using remote actors - fixed
import akka.actor.{Props, ActorRef, Actor, ActorSystem}
import TestActors._
import com.typesafe.config.ConfigFactory
object MainServer extends App {
start(asServer = true)
}
object MainClient extends App {
start(asServer = false)
}
object TestActors {
def start(asServer: Boolean) {
val system = ActorSystem("System", ConfigFactory.parseString(config(asServer)))
// val server = system.actorOf(Props[ServerActor], "ServerActor")
val server = if (asServer) {
system.actorOf(Props[ServerActor], "ServerActor")
} else {
system.actorFor("akka://System@localhost:" + serverPort + "/user/ServerActor")
}
val client = system.actorOf(Props[ClientActor])
server !('sub, client)
while (true) {
server ! 'pub
Console.readLine()
}
}
val ports = 2553 :: 2554 :: Nil
val serverPort = ports(0)
def config(asServer: Boolean): String = {
"""
akka {
remote {
transport = "akka.remote.netty.NettyRemoteTransport"
netty {
hostname = "localhost"
port = """ + (if (asServer) serverPort else ports(1)) + """
}
}
actor {
provider = "akka.remote.RemoteActorRefProvider"
}
}
"""
}
class ServerActor extends Actor {
override def preStart() {
println("Starting ServerActor")
}
var clients = List[ActorRef]()
protected def receive = {
case ('sub, sender: ActorRef) => clients ::= sender
case 'pub => clients.foreach(_ ! 'hello)
}
}
class ClientActor extends Actor {
protected def receive = {
case m => println(m)
}
}
}
@OlegYch

OlegYch commented Mar 23, 2012

Copy link
Copy Markdown
Author

how to have ServerActor be created only in jvm running MainServer ?

@OlegYch

OlegYch commented Mar 24, 2012

Copy link
Copy Markdown
Author

using akka 2.0
is this possible without using asServer variable and only by changing configuration?

@rkuhn

rkuhn commented Mar 25, 2012

Copy link
Copy Markdown

The code looks adequate for solving the problem which I can derive from what the code does. If you are unhappy, you should state which requirements this violates, i.e. what you really want to achieve. In the end you’ll have to start different jobs for Client and Server, no matter how you configure them. Possibilities include: different config files, system properties, querying an external config source, checking the hostname, …

@OlegYch

OlegYch commented Mar 25, 2012

Copy link
Copy Markdown
Author

Thanks, Roland. My main concern is tight coupling to the way actor is created or looked up, which i'd like to resolve via configuration (akin to dependency injection). Please see my post on ml.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment