WebSockets + Akka, on Scalatra


Yuvi Masory - @ymasory

Bay Area Scalatra Hackers (BASH)

January 30, 2013



Slides live at http://yuvimasory.com/talks.

What is this group about?

Is this the last BASH meetup?

Where are we going?

Some banter

ScalaTypes podcast - http://scalatypes.com

/Advertisement

Warning

Section I
Intro to Scalatra

Hello Scalatra

    import org.scalatra._

    class HelloScalatra extends ScalatraServlet {

      get("/") {
        "Hello, world!"
      }
    }
  

BEFORE I FORGET!

Scalatra's philosophy: transparency

Scalatra's philosophy: unobtrusiveness

Scalatra's philosophy: scalability

Scalatra's philosophy:
don't reinvent the wheel!

The dark side of Scalatra ...

Section II
Intro to WebSockets

HTTP history

What are WebSockets?

Browser support

HTTP handshake

    GET /mychat HTTP/1.1
    Host: server.example.com
    Upgrade: websocket
    Connection: Upgrade
    Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
    Sec-WebSocket-Protocol: chat
    Sec-WebSocket-Version: 13
    Origin: http://example.com
    Server response:
    HTTP/1.1 101 Switching Protocols
    Upgrade: websocket
    Connection: Upgrade
    Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
    Sec-WebSocket-Protocol: chat
  

Advantages of WebSockets

Disadvantages of WebSockets

Section III
Intro to Akka

What is Akka?

Actors in one slide

Actors are objects that ...

Sound familiar?

What Akka looks like

    class MyActor extends Actor {

      var count = 0

      def receive = {
        case "hi" => sender ! "and hello to you"

        case Inc =>
          count += 1
          sender ! count

        case quotesRequest: GetStockQuotes =>
          actorOf[StockChecker] ! (quotesRequest, sender)
      }
    }

    val ref: ActorRef = actorOf[MyActor]
    val res: Future[Any] = ref ? Inc
    res foreach println
  

Section IV
Mashup!

Atmosphere

Scalatra's Atmosphere integration

class ChatController extends ScalatraServlet 
  with JValueResult with JacksonJsonSupport    //let's use json!
  with SessionSupport with AtmosphereSupport { //let's use atmosphere!

  atmosphere("/the-chat") {
    new AtmosphereClient {
      def receive = { //this is a *partial* function, just like Akka
        case Connected =>
          broadcast(
            ("author" -> "Someone") ~
            ("message" -> "joined the room"))
          send("welcome!")
        case Disconnected(ClientDisconnected, cause) =>
        case Disconnected(ServerDisconnected, cause) =>
        case TextMessage(str) =>
        case JsonMessage(json) =>
        case BinaryMessage(array) =>
      }
    }
  }
  

Conclusion

My opinion

Thanks!

The end.

/

#