Client-Server example with Scala actors

空扰寡人 提交于 2019-12-05 04:25:14
import scala.actors._
import Actor._

case class SendRequest(rid: String)
case class Request(rid: String)
case class Response(rid: String)

val server = actor {
   eventloop {
         case Request(rid) => 
            println("Server got request [%s] from client" format(rid))
        sender ! Response(rid)  
      }
   }   
}

val client = actor {
   eventloop {
         case SendRequest(rid) => server ! Request(rid)
         case Response(rid) => 
            println("Client got response [%s] from server" format(rid))
      }
   }
}

Usage:

scala> client ! SendRequest("Hello!")
Server got request [Hello!] from client
Client got response [Hello!] from server

With regards to:

All this communication is asynchronous and hence it uses react.

Actors that use receive are also asynchronous. They just block the thread, waiting for a new messages.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!