• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala MessageFlowTransformer类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中play.api.mvc.WebSocket.MessageFlowTransformer的典型用法代码示例。如果您正苦于以下问题:Scala MessageFlowTransformer类的具体用法?Scala MessageFlowTransformer怎么用?Scala MessageFlowTransformer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了MessageFlowTransformer类的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: identifier

//设置package包名称以及导入依赖的类
package protocol

import play.api.libs.json._
import play.api.mvc.WebSocket.MessageFlowTransformer

sealed trait InEvent

sealed trait OutEvent

trait JSFormatter {
  def identifier = getClass.getSimpleName.dropRight(1)
}

object Messages {

  implicit object Writes extends Writes[OutEvent] {
    override def writes(o: OutEvent): JsValue = {
      o match {
        case i: IndividualInfo => IndividualInfo.format.writes(i)
        case s: Statistics => Statistics.format.writes(s)
        case x => sys.error("type not found " + o)
      }
    }
  }

  implicit object Reads extends Reads[InEvent] {
    override def reads(json: JsValue): JsResult[InEvent] = {
      val msgType = (json \ "msg").as[String]
      msgType match {
        case "start" => Start.format.reads(json)
      }
    }
  }

  case class Start(cycles: Int) extends InEvent

  object Start {
    implicit val format = Json.format[Start]
  }

  case class IndividualInfo(generation: Int, image: String, msg: String = IndividualInfo.identifier, population: Int, info: String)
      extends OutEvent

  object IndividualInfo extends JSFormatter {
    implicit val format = Json.format[IndividualInfo]
  }

  case class Statistics(message: String, msg: String = Statistics.identifier) extends OutEvent

  object Statistics extends JSFormatter {
    implicit val format = Json.format[Statistics]
  }

  implicit val messageFlowTransformer =
    MessageFlowTransformer.jsonMessageFlowTransformer[InEvent, OutEvent]

} 
开发者ID:coding-jam,项目名称:lagioconda,代码行数:58,代码来源:Protocol.scala


示例2: MessageFlowTransformerUtil

//设置package包名称以及导入依赖的类
package walfie.gbf.raidfinder.server.util

import akka.stream._
import akka.stream.scaladsl._
import com.trueaccord.scalapb.json.JsonFormat
import play.api.http.websocket._
import play.api.libs.streams._
import play.api.mvc.WebSocket.MessageFlowTransformer
import scala.util.control.NonFatal
import scala.util.Try
import walfie.gbf.raidfinder.protocol._

object MessageFlowTransformerUtil {
  private type ProtobufMessageFlowTransformer = MessageFlowTransformer[RequestMessage, BinaryProtobuf]

  // Throwing a WebSocketCloseException doesn't seem to actually propagate the
  // close reason to the client, despite what the ScalaDoc page says.
  // https://www.playframework.com/documentation/2.5.x/api/scala/index.html#play.api.http.websocket.WebSocketCloseException
  private def closeWebsocket(binary: Boolean): WebSocketCloseException = {
    val closeMessage = CloseMessage(Some(CloseCodes.InconsistentData), "Invalid input")
    WebSocketCloseException(closeMessage)
  }

  implicit val protobufJsonMessageFlowTransformer: ProtobufMessageFlowTransformer = {
    MessageFlowTransformer.stringMessageFlowTransformer.map(
      s => Try(JsonFormat.fromJsonString[RequestMessage](s))
        .getOrElse(throw closeWebsocket(binary = false)),
      binary => JsonFormat.toJsonString(
        ResponseMessage
          .validate(binary.value)
          .getOrElse(throw closeWebsocket(binary = false))
      )
    )
  }

  implicit val protobufBinaryMessageFlowTransformer: ProtobufMessageFlowTransformer = {
    MessageFlowTransformer.byteArrayMessageFlowTransformer.map(
      RequestMessage.validate(_).getOrElse(throw closeWebsocket(binary = true)),
      _.value
    )
  }
} 
开发者ID:walfie,项目名称:gbf-raidfinder,代码行数:43,代码来源:MessageFlowTransformerUtil.scala


示例3: WebsocketController

//设置package包名称以及导入依赖的类
package walfie.gbf.raidfinder.server.controller

import akka.actor._
import akka.stream.scaladsl.Flow
import akka.stream.{Materializer, OverflowStrategy}
import monix.execution.Scheduler
import play.api.http.websocket.Message
import play.api.libs.streams._
import play.api.mvc._
import play.api.mvc.WebSocket.MessageFlowTransformer
import scala.concurrent.duration.FiniteDuration
import scala.concurrent.Future
import walfie.gbf.raidfinder.domain._
import walfie.gbf.raidfinder.protocol._
import walfie.gbf.raidfinder.RaidFinder
import walfie.gbf.raidfinder.server.actor.WebsocketRaidsHandler
import walfie.gbf.raidfinder.server.util.MessageFlowTransformerUtil
import walfie.gbf.raidfinder.server.{BossNameTranslator, MetricsCollector}

class WebsocketController(
  raidFinder:        RaidFinder[BinaryProtobuf],
  translator:        BossNameTranslator,
  keepAliveInterval: FiniteDuration,
  metricsCollector:  MetricsCollector
)(implicit system: ActorSystem, materializer: Materializer, scheduler: Scheduler) extends Controller {
  private val jsonTransformer = MessageFlowTransformerUtil.protobufJsonMessageFlowTransformer
  private val binaryTransformer = MessageFlowTransformerUtil.protobufBinaryMessageFlowTransformer
  private val defaultTransformer = jsonTransformer

  
        val flow = ActorFlow.actorRef(props = props)
        transformer.transform(flow)
      }
      case None => Left {
        val unsupportedProtocols = requestedProtocols.mkString("[", ", ", "]")
        Results.BadRequest("Unsupported websocket subprotocols " + unsupportedProtocols)
      }
    }

    Future.successful(result)
  }
} 
开发者ID:walfie,项目名称:gbf-raidfinder,代码行数:43,代码来源:WebsocketController.scala


示例4: MessageFlowTransformerUtil

//设置package包名称以及导入依赖的类
package walfie.gbf.raidfinder.server.util

import akka.stream._
import akka.stream.scaladsl._
import com.trueaccord.scalapb.json.JsonFormat
import play.api.http.websocket._
import play.api.libs.streams._
import play.api.mvc.WebSocket.MessageFlowTransformer
import scala.util.control.NonFatal
import scala.util.Try
import walfie.gbf.raidfinder.protocol._

object MessageFlowTransformerUtil {
  private type ProtobufMessageFlowTransformer = MessageFlowTransformer[RequestMessage, ResponseMessage]

  // Throwing a WebSocketCloseException doesn't seem to actually propagate the
  // close reason to the client, despite what the ScalaDoc page says.
  // https://www.playframework.com/documentation/2.5.x/api/scala/index.html#play.api.http.websocket.WebSocketCloseException
  private def closeWebsocket(binary: Boolean): WebSocketCloseException = {
    val closeMessage = CloseMessage(Some(CloseCodes.InconsistentData), "Invalid input")
    WebSocketCloseException(closeMessage)
  }

  implicit val protobufJsonMessageFlowTransformer: ProtobufMessageFlowTransformer = {
    MessageFlowTransformer.stringMessageFlowTransformer.map(
      s => Try(JsonFormat.fromJsonString[RequestMessage](s))
        .getOrElse(throw closeWebsocket(binary = false)),
      JsonFormat.toJsonString(_)
    )
  }

  implicit val protobufBinaryMessageFlowTransformer: ProtobufMessageFlowTransformer = {
    MessageFlowTransformer.byteArrayMessageFlowTransformer.map(
      RequestMessage.validate(_).getOrElse(throw closeWebsocket(binary = true)),
      _.toByteArray
    )
  }
} 
开发者ID:Einhalkzt,项目名称:GBF-RAid-finder,代码行数:39,代码来源:MessageFlowTransformerUtil.scala


示例5: WebsocketController

//设置package包名称以及导入依赖的类
package walfie.gbf.raidfinder.server.controller

import akka.actor._
import akka.stream.scaladsl.Flow
import akka.stream.{Materializer, OverflowStrategy}
import monix.execution.Scheduler
import play.api.http.websocket.Message
import play.api.libs.streams._
import play.api.mvc._
import play.api.mvc.WebSocket.MessageFlowTransformer
import scala.concurrent.duration.FiniteDuration
import scala.concurrent.Future
import walfie.gbf.raidfinder.domain._
import walfie.gbf.raidfinder.protocol._
import walfie.gbf.raidfinder.RaidFinder
import walfie.gbf.raidfinder.server.actor.WebsocketRaidsHandler
import walfie.gbf.raidfinder.server.util.MessageFlowTransformerUtil
import walfie.gbf.raidfinder.server.{BossNameTranslator, MetricsCollector}

class WebsocketController(
  raidFinder:        RaidFinder[ResponseMessage],
  translator:        BossNameTranslator,
  keepAliveInterval: FiniteDuration,
  metricsCollector:  MetricsCollector
)(implicit system: ActorSystem, materializer: Materializer, scheduler: Scheduler) extends Controller {
  private val jsonTransformer = MessageFlowTransformerUtil.protobufJsonMessageFlowTransformer
  private val binaryTransformer = MessageFlowTransformerUtil.protobufBinaryMessageFlowTransformer
  private val defaultTransformer = jsonTransformer

  
        val flow = ActorFlow.actorRef(props = props)
        transformer.transform(flow)
      }
      case None => Left {
        val unsupportedProtocols = requestedProtocols.mkString("[", ", ", "]")
        Results.BadRequest("Unsupported websocket subprotocols " + unsupportedProtocols)
      }
    }

    Future.successful(result)
  }
} 
开发者ID:Einhalkzt,项目名称:GBF-RAid-finder,代码行数:43,代码来源:WebsocketController.scala


示例6: MyApplicationController

//设置package包名称以及导入依赖的类
package my.samples.controllers

import play.api.mvc._
import my.samples.core.AppBindings
import play.api.libs.json.JsValue
import play.api.libs.streams.ActorFlow
import play.api.mvc.WebSocket.MessageFlowTransformer

final class MyApplicationController(bindings: AppBindings) extends Controller {

  implicit val messageFlowTransformer =
    MessageFlowTransformer.jsonMessageFlowTransformer[JsValue, JsValue]

  implicit val actorSystem = bindings.actorSystem
  implicit val materializer = bindings.materializer

  def home = Action { implicit request =>
    Ok("The API is ready")
  }

  def observable = WebSocket.accept[JsValue, JsValue] { request =>
    ActorFlow.actorRef(out => MyWebSocketActor.props(bindings.globalChannel.publishChannel, out))
  }

  def connectableObservable = WebSocket.accept[JsValue, JsValue] { request =>
    ActorFlow.actorRef(out => MyWebSocketActor.props(bindings.globalChannel.publishChannel, out))
  }
} 
开发者ID:joesan,项目名称:monix-samples,代码行数:29,代码来源:MyApplicationController.scala


示例7: MyWebSocketActor

//设置package包名称以及导入依赖的类
package actors

import akka.actor.{ActorRef, Actor, Props}
import play.api.libs.json._
import play.api.mvc.WebSocket.MessageFlowTransformer

object MyWebSocketActor {

  case class InEvent(message: String)
  object InEvent {
    implicit val inEventFormat: OFormat[InEvent] = Json.format[InEvent]
  }

  case class OutEvent(message: String)
  object OutEvent {
    implicit val outEventFormat: OFormat[OutEvent] = Json.format[OutEvent]
  }

  implicit val messageFlowTransformer: MessageFlowTransformer[InEvent, OutEvent] =
    MessageFlowTransformer.jsonMessageFlowTransformer[InEvent, OutEvent]

  def props(out: ActorRef) = Props(new MyWebSocketActor(out))
}

class MyWebSocketActor(out: ActorRef) extends Actor {
  import MyWebSocketActor._

  def receive: Receive = {
    case msg: InEvent => out ! OutEvent("I received your message : " + msg)
  }
} 
开发者ID:stonexx,项目名称:utils,代码行数:32,代码来源:MyWebSocketActor.scala


示例8: Application

//设置package包名称以及导入依赖的类
package controllers

import javax.inject.Inject

import akka.stream.scaladsl.Flow
import akka.util.ByteString
import models.{Project, ProjectRepo}
import play.api.http.HttpEntity.Streamed
import play.api.http.MimeTypes
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json.{JsSuccess, Json}
import play.api.mvc.WebSocket.MessageFlowTransformer
import play.api.mvc._

import scala.concurrent.duration._

class Application @Inject()(projectRepo: ProjectRepo) extends Controller {

  implicit val mt: MessageFlowTransformer[Project, String] = {
    MessageFlowTransformer.stringMessageFlowTransformer.map { s =>
      Json.fromJson[Project](Json.parse(s)) match {
        case JsSuccess(project, _) => project
      }
    }
  }


  def socket = WebSocket.accept[Project, String] { request =>
    Flow[Project]
      .groupedWithin(10, 10 millis)
      .map(_.toList)
      .mapAsyncUnordered(parallelism = 4)(projectRepo.insert)
      .map(_.n.toString)
  }

  def createProject(name: String) = Action.async {
    projectRepo.create(name)
      .map(id => Ok(s"project $id created"))
  }

  def listProjects = Action {
    val projects = projectRepo.all
      .map(p => Json.toJson[List[Project]](p))
      .map(js => ByteString(js.toString()))

    Ok.sendEntity(Streamed(projects, None, Some(MimeTypes.JSON)))
  }

  def projects(name: String) = Action.async {
    for {
      Some(project) <- projectRepo.findByName(name)
    } yield Ok(Json.toJson(project))
  }

} 
开发者ID:jonasanso,项目名称:play-tepkin-mongo,代码行数:56,代码来源:Application.scala


示例9: Formats

//设置package包名称以及导入依赖的类
package models

import play.api.libs.json._
import play.api.mvc.WebSocket.MessageFlowTransformer
import shared.{Direction, Down, Left, Right, SnakeState, Up, Vector2, WorldState}


object Formats {
  implicit val directionFormat = new Format[Direction] {
    override def writes(o: Direction): JsValue = JsString(o.value)
    override def reads(json: JsValue): JsResult[Direction] = json match {
      case JsString(Up.value) => JsSuccess(Up)
      case JsString(Down.value) => JsSuccess(Down)
      case JsString(Left.value) => JsSuccess(Left)
      case JsString(Right.value) => JsSuccess(Right)
      case _ => JsError(s"invalid direction ${json}")
    }
  }

  implicit val vector2Format = Json.writes[Vector2]
  implicit val snakeStateFormat = Json.writes[SnakeState]
  implicit val stateFormat = Json.writes[WorldState]
  implicit val transformer = MessageFlowTransformer.jsonMessageFlowTransformer[Direction, WorldState]

} 
开发者ID:lenstr,项目名称:horrible-snake,代码行数:26,代码来源:Formats.scala


示例10: WebSocketController

//设置package包名称以及导入依赖的类
package controllers

import javax.inject.Inject

import actors.{MessageActor, RoomActor, RoomClientActor, RoomMasterActor}
import akka.actor.ActorSystem
import akka.stream.Materializer
import json.{IncomingMessage, IncomingRoomMessage, OutgoingMessage, OutgoingRoomMessage}
import play.api.libs.json.Json
import play.api.libs.streams.ActorFlow
import play.api.mvc.WebSocket.MessageFlowTransformer
import play.api.mvc.{Controller, WebSocket}


class WebSocketController @Inject() (implicit system: ActorSystem, materializer: Materializer) extends Controller{
  
  implicit val inMessageFormat = Json.format[IncomingMessage]
  implicit val outMessageFormat = Json.format[OutgoingMessage]
  implicit val inRoomMessageFormat = Json.format[IncomingRoomMessage]
  implicit val outRoomMessageFormat = Json.format[OutgoingRoomMessage]
  
  implicit val messageFlowTransformer = MessageFlowTransformer.jsonMessageFlowTransformer[IncomingMessage, OutgoingMessage]
  implicit val roomFlowTransformer = MessageFlowTransformer.jsonMessageFlowTransformer[IncomingRoomMessage, OutgoingRoomMessage]
  
  def messageWebSocket(userId: String) = WebSocket.accept[IncomingMessage, OutgoingMessage] {
    request => ActorFlow.actorRef(out => MessageActor.props(out, userId))
  }
  
  def roomWebSocket(userId: String) = WebSocket.accept[IncomingRoomMessage, OutgoingRoomMessage] {
    request => ActorFlow.actorRef(out => RoomClientActor.props(out, userId))
  }
  
} 
开发者ID:dazito,项目名称:messengr,代码行数:34,代码来源:WebSocketController.scala


示例11: HomeController

//设置package包名称以及导入依赖的类
package controllers

import akka.actor.ActorSystem
import akka.stream._
import javax.inject._
import play.api._
import play.api.libs.json._
import play.api.libs.streams._
import play.api.mvc._
import play.api.mvc.WebSocket.MessageFlowTransformer
import scala.concurrent.duration._
import scala.concurrent.{ ExecutionContext, Future, Promise }

import actors._
import models._

@Singleton
class HomeController @Inject() (implicit actorSystem: ActorSystem, materializer: Materializer, exec: ExecutionContext) extends Controller {

  val game = actorSystem.actorOf(GameActor.props)

  implicit val messageFlowTransformer =
    MessageFlowTransformer.jsonMessageFlowTransformer[InEvent, OutEvent]

  def connect(team: String) = WebSocket.acceptOrResult[InEvent, OutEvent] { request =>
    Future.successful {
      Color.get(team) match {
      case None =>
        Left(NotFound)
      case Some(color) =>
        Right(ActorFlow.actorRef(ws =>
          PlayerActor.props(ws, game, color)
        ))
      }
    }
  }

  def home(team: Option[String]) = Action { implicit request =>
    team match {
      case None =>
        Redirect(routes.HomeController.home(Some(Player.genColor().name)))
      case Some(team) =>
        Ok(views.html.index(routes.HomeController.connect(team).webSocketURL))
    }
  }

  def info = Action.async {
    val p = Promise[JsValue]()
    game ! GameInfo(p)
    p.future.map { info =>
      Ok(info)
    }
  }

} 
开发者ID:dohzya,项目名称:clostrotaupe,代码行数:56,代码来源:HomeController.scala


示例12: TaskController

//设置package包名称以及导入依赖的类
package controllers

import actors.TaskActor
import akka.actor.ActorRef
import akka.actor.ActorSystem
import akka.actor.Props
import akka.stream.Materializer
import dao.TaskDao
import javax.inject._
import models.Task
import play.api.libs.json.Json
import play.api.libs.streams.ActorFlow
import play.api.mvc._
import play.api.mvc.WebSocket.MessageFlowTransformer
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import service.TaskService
import akka.actor.ActorSystem
import forms.TaskForm

@Singleton
class TaskController @Inject() (implicit actorSystem: ActorSystem, materializer: Materializer, taskService: TaskService) extends Controller {
	implicit val inEventFormat = Json.format[TaskForm]
	implicit val outEventFormat = Json.format[Result]
	implicit val messageFlowTransformer = MessageFlowTransformer.jsonMessageFlowTransformer[TaskForm, Result]
	
	def task = Action.async { implicit request =>
		taskService.getAllTask().map { case tasks => Ok(views.html.task(tasks)) }
	}
	
	def wsTask = WebSocket.accept[TaskForm, Result] { request =>
		ActorFlow.actorRef[TaskForm, Result] { out =>
			TaskActor.props(out, taskService)
		}
	}
}

case class Result(result:Boolean,mode:String, data: String) 
开发者ID:tyutyu08,项目名称:testScalaPlay,代码行数:38,代码来源:TaskController.scala


示例13: SocketController

//设置package包名称以及导入依赖的类
package controllers

import javax.inject.Inject

import akka.actor.ActorSystem
import akka.stream.Materializer
import entities.{FrontEndQuote, Quote}
import models.actors.StockUpdateActor
import models.persistence.QuotePersistence
import play.api.libs.streams.ActorFlow
import play.api.mvc.{Action, Controller, WebSocket}

import scala.concurrent.ExecutionContext
import play.api.mvc.WebSocket.{FrameFormatter, MessageFlowTransformer}


class SocketController @Inject()(quoteDAO: QuotePersistence, implicit val system: ActorSystem, implicit val materializer: Materializer)
                       (implicit ec: ExecutionContext) extends Controller {

  import models.util.JsonConverters._
  implicit val messageFlowTransformer = MessageFlowTransformer.jsonMessageFlowTransformer[String, FrontEndQuote]

  def index = Action { request =>
    Ok(views.html.index.render())
  }

  def socket: WebSocket = WebSocket.accept[String, FrontEndQuote] { request =>
    ActorFlow.actorRef(out => StockUpdateActor.props(out, quoteDAO))
  }
} 
开发者ID:tomliddle,项目名称:stock-quotes,代码行数:31,代码来源:SocketController.scala



注:本文中的play.api.mvc.WebSocket.MessageFlowTransformer类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala Throw类代码示例发布时间:2022-05-23
下一篇:
Scala JacksonFactory类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap