TrexXx February 2016

Websocket with async handler

I can't get Akka http websockets to work with connection.handleWithAsyncHandler. Here is my code in scala (i'm using the latest version of akka http)

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.model._
import akka.http.scaladsl.model.ws.{Message, UpgradeToWebsocket}
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{Flow, Sink}

import scala.concurrent.Future

object Server extends App {
    implicit val system = ActorSystem("server-system")
    implicit val materializer = ActorMaterializer()
    implicit val dispatcher = system.dispatcher
    implicit val formats = net.liftweb.json.DefaultFormats

    val serverSource = Http().bind(interface = "localhost", port = 9000)

    val requestHandler: HttpRequest => Future[HttpResponse] = {
        case request @ HttpRequest(GET, Uri.Path("/websocket"), _, _, _) => {
            Future {
                request.header[UpgradeToWebsocket] match {
                    case Some(upgrade) => {
                        upgrade.handleMessages(Flow[Message])
                    }
                    case None => {
                        HttpResponse(StatusCodes.BadRequest)
                    }
                }
            }
        }
        case _: HttpRequest => {
            Future.successful(HttpResponse(StatusCodes.BadRequest))
        }
    }

    val bindingFuture = serverSource.to(Sink.foreach { connection =>
        connection.handleWithAsyncHandler(requestHandler)
    }).run()
}

and my JS code to test it:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
<script>
    var ws = new WebSocket('ws://localhost:9000/websocket');

    ws.onopen = function() {
        console.log('open');

        ws.send('test message');
    };

        

Answers


TrexXx February 2016

Updating to akka 2.4.2-RC2 did the trick.

Post Status

Asked in February 2016
Viewed 2,577 times
Voted 14
Answered 1 times

Search




Leave an answer