Scala Client-Server Example

What is the best way to implement the following example?

  • The server actor receives Requests , processes them, creates a new Response for each Request and sends a Response back to the Request sender.

  • The client actor sends Requests and receives Responses .

All this message is asynchronous and therefore uses react .

This is just an example, so it should not handle all those cases when the server is down, the client stuck, etc. It should be simply concise and expressive.

+7
source share
1 answer
 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)) } } } 

Using:

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

Concerning:

All this message is asynchronous and therefore it uses a reaction.

Actors who use receive are also asynchronous. They simply block the flow, waiting for new messages.

+8
source

All Articles