Scala Akka网络编程:Client Server网络通信(你问我答)案例
生活随笔
收集整理的這篇文章主要介紹了
Scala Akka网络编程:Client Server网络通信(你问我答)案例
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
最終效果
Server端
package cn.zxl.akka.serverimport akka.actor._ import cn.zxl.akka.common.{ClientMessage, ServerMessage} import com.typesafe.config.ConfigFactory/*** @description:* @author: zhangxueliang* @create: 2021-05-29 16:07* @version: 1.0* */ class YellowChickenServer extends Actor{override def receive: Receive = {case "start" => println("start 小黃雞客服開始工作了....")//如果接收到 ClientMessagecase ClientMessage(mes) => {//使用 match --case 匹配(模糊)mes match {case "大數據學費" => sender() ! ServerMessage("35000RMB")case "學校地址" => sender() ! ServerMessage("北京昌平 xx 路 xx 大樓")case "學習什么技術" => sender() ! ServerMessage("大數據 前端 python")case _ => sender() ! ServerMessage("你說的啥子~")}}} }object YellowChickenServer extends App {val host = "127.0.0.1" //服務端 ip 地址val port = 9999//創建 config 對象,指定協議類型,監聽的 ip 和端口val config = ConfigFactory.parseString(s"""|akka.actor.provider="akka.remote.RemoteActorRefProvider"|akka.remote.netty.tcp.hostname=$host|akka.remote.netty.tcp.port=$port """.stripMargin)//創建 ActorSystem//url (統一資源定位)val serverActorSystem =ActorSystem("Server",config)//創建 YellowChickenServer 的 actor 和返回 actorRefval yellowChickenServerRef: ActorRef =serverActorSystem.actorOf(Props[YellowChickenServer],"YellowChickenServer")//啟動yellowChickenServerRef ! "start" }Client端
package cn.zxl.akka.clientimport akka.actor.{Actor, ActorRef, ActorSelection, ActorSystem, Props} import cn.zxl.akka.common.{ClientMessage, ServerMessage} import com.typesafe.config.ConfigFactoryimport scala.io.StdIn/*** @description:* @author: zhangxueliang* @create: 2021-05-29 16:10* @version: 1.0* */ class CustomerActor(serverHost: String, serverPort: Int) extends Actor {//定義一個 YellowChickenServerRefvar serverActorRef: ActorSelection = _//在 Actor 中有一個方法 PreStart 方法,他會在 actor 運行前執行//在 akka 的開發中,通常將初始化的工作,放在 preStart 方法override def preStart(): Unit = {println("preStart() 執行")serverActorRef =context.actorSelection(s"akka.tcp://Server@${serverHost}:${serverPort}/user/YellowChickenServer")println("serverActorRef=" + serverActorRef)}override def receive: Receive = {case "start" => println("start,客戶端運行,可以咨詢問題")case mes: String => {//發給小黃雞客服serverActorRef ! ClientMessage(mes) //使用 ClientMessage case class apply}//如果接收到服務器的回復case ServerMessage(mes) => {println(s"收到小黃雞客服(Server): $mes")}} }//主程序-入口 object CustomerActor extends App {val (clientHost, clientPort, serverHost, serverPort) = ("127.0.0.1", 9990, "127.0.0.1", 9999)val config = ConfigFactory.parseString(s"""|akka.actor.provider="akka.remote.RemoteActorRefProvider"|akka.remote.netty.tcp.hostname=$clientHost|akka.remote.netty.tcp.port=$clientPort """.stripMargin)//創建 ActorSystemval clientActorSystem = ActorSystem("client", config)//創建 CustomerActor 的實例和引用val customerActorRef: ActorRef = clientActorSystem.actorOf(Props(new CustomerActor(serverHost,serverPort)), "CustomerActor")//啟動 customerRef/也可以理解啟動 ActorcustomerActorRef ! "start"//客戶端可以發送消息給服務器while (true) {println("請輸入要咨詢的問題")val mes = StdIn.readLine()customerActorRef ! mes} }樣例類:ClientMessage和ServerMessage
package cn.zxl.akka.common/*** @description:* @author: zhangxueliang* @create: 2021-05-29 16:14* @version: 1.0* */ //使用樣例類來構建協議 //客戶端發給服務器協議(序列化的對象) case class ClientMessage(mes: String) //服務端發給客戶端的協議(樣例類對象) case class ServerMessage(mes: String)pom
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.zxl</groupId><artifactId>scala-demo</artifactId><version>1.0-SNAPSHOT</version><packaging>jar</packaging><name>scala-demo</name><url>http://maven.apache.org</url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><encoding>UTF-8</encoding><scala.version>2.11.12</scala.version><scala.compat.version>2.11</scala.compat.version><akka.version>2.5.12</akka.version><scala.actors.version>2.10.0-M6</scala.actors.version></properties><dependencies><!--scala 2.11起過時 無法使用--><!--<dependency><groupId>org.scala-lang</groupId><artifactId>scala-actors</artifactId><version>${scala.actors.version}</version></dependency>--><!--akka actor依賴--><dependency><groupId>com.typesafe.akka</groupId><artifactId>akka-actor_${scala.compat.version}</artifactId><version>${akka.version}</version></dependency><!--多進程之間的Actor通信--><dependency><groupId>com.typesafe.akka</groupId><artifactId>akka-remote_${scala.compat.version}</artifactId><version>${akka.version}</version></dependency></dependencies><build><!--指定源碼包和測試包的位置--><sourceDirectory>src/main/scala</sourceDirectory><testSourceDirectory>src/test/scala</testSourceDirectory><plugins><!-- 該插件用于將 Scala 代碼編譯成 class 文件 --><plugin><groupId>net.alchim31.maven</groupId><artifactId>scala-maven-plugin</artifactId><version>3.2.2</version><executions><execution><!-- 聲明綁定到 maven 的 compile 階段 --><goals><goal>compile</goal><goal>testCompile</goal></goals><configuration><args><arg>-dependencyfile</arg><arg>${project.build.directory}/.scala_depencencies</arg></args></configuration></execution></executions></plugin><!--maven打包的插件--><!-- maven-assembly-plugin 和 maven-shade-plugin都是打包插件。遇到同名文件assembly是覆蓋,shade是追加。所以此處選擇shade插件--><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-shade-plugin</artifactId><version>3.2.1</version><executions><execution><phase>package</phase><goals><goal>shade</goal></goals><configuration><filters><filter><artifact>*:*</artifact><excludes><exclude>META-INF/*.SF</exclude><exclude>META-INF/*.DSA</exclude><exclude>META-INF/*.RSA</exclude></excludes></filter></filters><transformers><transformerimplementation="org.apache.maven.plugins.shade.resource.AppendingTransformer"><resource>reference.conf</resource></transformer><!--指定main方法--><transformerimplementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"><mainClass>xxx</mainClass></transformer></transformers></configuration></execution></executions></plugin></plugins></build> </project>總結
以上是生活随笔為你收集整理的Scala Akka网络编程:Client Server网络通信(你问我答)案例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Scala Actor并发编程入门示例
- 下一篇: Scala基于Akka模拟Spark M