Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Websocket with async handler

Tags:

akka

akka-http

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');
    };

    ws.onmessage = function(msg) {
        console.log(msg.data);
    };

    ws.onclose = function() {
        console.log('close');
    };
</script>
</body>
</html>

In the console I get

open
close

Why is websocket connection closed directly after being opened ?

like image 393
mravey Avatar asked Nov 09 '22 20:11

mravey


1 Answers

Updating to akka 2.4.2-RC2 did the trick.

like image 122
mravey Avatar answered Dec 15 '22 02:12

mravey