Scala HTTP Server pt 2

Here is the runner class for my HTTP Server. It is ‘runnable’ – has a main method – and has a Logger using a trait called Logging.

The main method is provided by the ‘extends App’ which creates an instance of the class inside a virtual ‘main’ method we don’t see here, equivalent to

class Runner {
  private Runner() { 
    // code here to create system and server...

  public static void main(String[] args) {
     new Runner()

The ‘with Logging’ gives this class functionality defined in the Logging trait, where a trait is a way of reusing code without normal java-style inheritance but halfway to composition. The Logging trait defines that this class has a log4j Logger and a method ‘info’ which calls the info method on the Logger.

This line

server ! StartListening(numberOfThreads = 10)

sends a message of type ‘StartListening’ to the server Actor. This syntax is standard akka and beyond the scope of this small tutorial.

package com.vff.scalahttp

import com.vff.scalahttp.log.Logging

/** As invoked by Java process. */
object Runner extends App with Logging {

  val DEFAULT_PORT = 8000
  def port = if (args.length > 0) args(0).toInt else DEFAULT_PORT
  info(s"Creating server on port $port")

  val system = ActorSystem("akkaHttpServer")
  val server = system.actorOf(Props[ServerActor])

  server ! StartListening(numberOfThreads = 10)
  // Create the ActorSystem...
  info("Scala Http Server running")

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s