akka actor rpc demo

消息 “send:test”发给 clientActor 》》
》clientActor接收到,再发送 “test” 给serverActor 》》
》serverActor接收到,再回馈给clientActor》》
》clientActor收到并打印

服务器端为一个Actor,接收来自任意客户端发来的字符串消息,并把此消息原路返回

import akka.actor.{ActorRef, _}
import com.typesafe.config.ConfigFactory
class ServerActor extends Actor {
  override def receive: Receive = {
  case msg: String => {
  println("Server:Got message:" + msg)
  sender.tell("Server:" + msg,ActorRef.noSender)
  }
  case _ => println("ERROR MESSAGE TYPE... ")
  }
}

object Server {
  def main(args: Array[String]): Unit = {
  val serverSystem = ActorSystem("myServerSys", ConfigFactory.parseString(
  """
  akka {
  actor {
  provider = "akka.remote.RemoteActorRefProvider"
  }
  remote {
  enabled-transports = ["akka.remote.netty.tcp"]
  netty.tcp {
  hostname = "127.0.0.1"
  port = 9999
  }
  }
  } """))

  val serverActor=serverSystem.actorOf(Props(classOf[ServerActor]), "server")

  }
}

客户端也是一个Actor,
如果收到以“send”开头的字符串,就把这个字符串发送给代表服务器的Actor
如果收到的字符串不是以“send”开头,就表示是从服务器端那边回馈过来的,直接打印

import akka.actor._
import com.typesafe.config.ConfigFactory

class ClientActor extends Actor {

  var serverActor: ActorSelection = null

  @throws[Exception](classOf[Exception])
  override def preStart(): Unit = {
  serverActor = context.actorSelection("akka.tcp://[email protected]:9999/user/server")
  }

  override def receive: Receive = {
  case msg: String => {
  if (msg.startsWith("send:")) {
  println(msg.split(":")(1)+" will send to server")
  serverActor.tell(msg.split(":")(1),self)
  } else {
  println("Client:receive from server: " + msg)
  }
  }
  case _ => println("ERROR MESSAGE TYPE... ")
  }
}

object Client {
  def main(args: Array[String]): Unit = {
  val clientSystem = ActorSystem("myClientSys", ConfigFactory.parseString(
  """
  akka {
  actor {
  provider = "akka.remote.RemoteActorRefProvider"
  }
  }
  """))

  val clientActor = clientSystem.actorOf(Props(classOf[ClientActor]))

  clientActor.tell("send:test test test",ActorRef.noSender);
  clientActor.tell("send:test1 test test",ActorRef.noSender);
  clientActor.tell("send:test2 test test",ActorRef.noSender);

  }
}

Actor对象中的tell方法,
第一个参数表示要发送的消息,
第二个参数表示发送者,ActorRef.noSender表示不提供发送者,如果想让对方回馈或者发送给其他Actor对象 那么就要提供对应的Actor对象

你可能感兴趣的:(scala,scala)