16.5.2 Actor通过网络通讯
服务器客服Actor
package com.atguigu.akka.net
import akka.actor.{Actor, ActorRef, ActorSystem, Props}
import com.typesafe.config.{Config, ConfigFactory}
class ServerActor extends Actor {
override def receive: Receive = {
case msg: String => {
msg match {
case "start" => println("客服可以开始工作了...")
case a: String if a.contains("地址") => {
sender() ! "北京市 昌平路 xxxx"
}
case a: String if a.contains("学费") => {
sender() ! "大数据学费 20098 元"
}
case a: String if a.contains("技术") => {
sender() ! "大数据 java 前段 python 区块链"
}
case a: String => {
sender() ! "你说的话小妹没有听懂, 再说一遍..."
}
}
}
}
}
object ServerActor {
def main(args: Array[String]): Unit = {
val config: Config = ConfigFactory.parseString(
s"""
|akka.actor.provider="akka.remote.RemoteActorRefProvider"
|akka.remote.netty.tcp.hostname=192.168.43.250
|akka.remote.netty.tcp.port=10000
""".stripMargin)
val actorSystem: ActorSystem = ActorSystem("Server", config)
val serverActor: ActorRef = actorSystem.actorOf(Props(classOf[ServerActor]), "ServerActor")
serverActor ! "start"
}
}
客户Actor
package com.atguigu.akka.net
import akka.actor.{Actor, ActorRef, ActorSelection, ActorSystem, Props}
import com.typesafe.config.{Config, ConfigFactory}
import scala.io.StdIn
class ClientActor(serverHost: String, serverPort: Int) extends Actor {
var serverSelection: ActorSelection = _
override def preStart(): Unit = {
println(serverHost)
serverSelection = context.actorSelection(s"akka.tcp://Server@${serverHost}:${serverPort}/user/ServerActor")
}
override def receive: Receive = {
case "start" => {
println("客户端已经开启, 可以向客服咨询问题...")
serverSelection ! StdIn.readLine()
}
case msg: String => {
println("客服: " + msg)
serverSelection ! StdIn.readLine()
}
case _ => {
}
}
}
object ClientActor {
def main(args: Array[String]): Unit = {
val config: Config = ConfigFactory.parseString(
s"""
|akka.actor.provider="akka.remote.RemoteActorRefProvider"
|akka.remote.netty.tcp.hostname=192.168.43.250
|akka.remote.netty.tcp.port=9999
""".stripMargin)
val clientSystem: ActorSystem = ActorSystem("Client", config)
val clientActor: ActorRef = clientSystem.actorOf(Props(classOf[ClientActor], "192.168.43.250", 10000), "clientActor")
clientActor ! "start"
}
}
测试
步骤1: 启动服务器端
步骤2: 启动客户端