Last active
December 9, 2019 13:15
-
-
Save jonathonherbert/d4ad64b37e7ba866060971ab5a8a6754 to your computer and use it in GitHub Desktop.
Websockets example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// in ApiController body | |
def checkStream: WebSocket = WebSocket.accept[JsValue, JsValue] { _ => | |
ActorFlow.actorRef(out => | |
CheckStreamActor.props(out, matcherPool) | |
, | |
// A large buffer is necessary to ensure messages aren't dropped -- see | |
// https://github.com/playframework/playframework/issues/6246. | |
10000) | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package actors | |
import model.{Check, MatcherError, MatcherWorkComplete} | |
import play.api.libs.json.{JsValue, Json} | |
import services._ | |
import scala.concurrent.ExecutionContext | |
import akka.actor._ | |
import akka.stream.Materializer | |
import akka.stream.scaladsl.Sink | |
object CheckStreamActor { | |
def props(out: ActorRef, pool: MatcherPool)(implicit ec: ExecutionContext, mat: Materializer) = Props(new CheckStreamActor(out, pool)) | |
} | |
class CheckStreamActor(out: ActorRef, pool: MatcherPool)(implicit ec: ExecutionContext, implicit val mat: Materializer) extends Actor { | |
def receive: PartialFunction[Any, Unit] = { | |
case jsValue: JsValue => | |
jsValue.validate[Check].asEither match { | |
case Right(check) => { | |
pool.checkStream(check).map { | |
out ! Json.toJson(_) | |
}.runWith(Sink.ignore).onComplete { _ => | |
out ! Json.toJson(MatcherWorkComplete()) | |
out ! Success | |
} | |
} | |
case Left(error) => { | |
out ! Json.toJson(MatcherError(s"Error parsing websocket input: $error")) | |
out ! Failure | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment