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 ?
Updating to akka 2.4.2-RC2 did the trick.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With