1
votes

Suppose I need to implement a custom message-oriented protocol in Scala. I need to implement also the client/server code.

I would define "cases classes" for protocol messages as follows:

trait Message
case class Request1(...) extends Message
case class Response1(...) extends Message
case class Request2(...) extends Message
case class Response2(...) extends Message
... // other requests/responses

Now I need functions to read/write the messages from/to input/output streams and handle the messages.

def read(in: InputStream): Message = {...}

def write(msg: Message, out: OutputStream) {...}

def handle(msg:Message): Message = msg match {
  case req: Request1 = ... // handle Request1
  case resp: Response1 = ... // handle Response1
  ... // cases for all other message types
} 

I guess it works but I wonder if I can improve the solution. How would you correct or improve it ?

1

1 Answers

2
votes

Have you had a look at Akka?

Akk makes it much simpler to develop distributed applications, no need to define input and output streams manually. Just have a look at the "Remoting" example on the homepage.

The benefits of this approach would be that you can focus on the protocol itself, i.e., in your case the development of one (or more) actors on the client side, and one (or more) actors on the server side.

Akka should provide you with all 'lower-level' functionality you need, taking care of the actual sending an receiving of the messages, multi-threading, and so on; so you don't have to re-invent the wheel. This should also make your code easier to maintain by others in the future, as Akka is a well-known toolkit.

To get a basic idea of how actors work, have a look at this book chapter, but note that it describes the Scala actors, which have been replaced by Akka actors in the meantime. If you want to dig deeper, I'd recommend Akka Concurrency, which is more up to date.