akka - Websocket with async handler -
i can't akka http websockets work connection.handlewithasynchandler
. here code in scala (i'm using 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 js code 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 console get
open close
why websocket connection closed directly after being opened ?
updating akka 2.4.2-rc2 did trick.
Comments
Post a Comment