Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Client-Server example with Scala actors

Tags:

scala

actor

What is the best way to implement the following example ?

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

  • Actor client sends Requests and receives Responses.

All this communication is asynchronous and hence it uses react.

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

like image 285
Michael Avatar asked Jun 11 '11 16:06

Michael


1 Answers

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.

like image 178
Vasil Remeniuk Avatar answered Oct 04 '22 15:10

Vasil Remeniuk