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 java.net.ServerSocket
import java.net.Socket
import com.vff.scalahttp.log.Logging
import akka.actor.Actor
import akka.actor.ActorSystem
import akka.actor.Props
import akka.actor.ActorRef
import java.io.BufferedReader
import java.io.InputStreamReader

/** 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")
}