当前位置: 首页>>代码示例>>Scala>>正文


Scala Message类代码示例

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


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

示例1: WebSocketHandler

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

import akka.NotUsed
import akka.actor._
import akka.http.scaladsl.model.ws.{BinaryMessage, Message, TextMessage}
import akka.stream.scaladsl._
import akka.stream.{ActorMaterializer, OverflowStrategy}
import core.entities.AuthTokenContext
import websocket.ClientEndpoint._
import websocket.WebSocketHandler._

import scala.concurrent.ExecutionContext
import scala.concurrent.duration.FiniteDuration

class WebSocketHandler(processingRouter: ActorRef, connectedClientsStore: ActorRef, processingTimeout: FiniteDuration)
                      (implicit system: ActorSystem, mat: ActorMaterializer, apiDispatcher: ExecutionContext) {

  def clientEndpoint(ctx: AuthTokenContext): Flow[Message, Message, NotUsed] = {
    val clientEndpoint =
      system.actorOf(ClientEndpoint.props(ctx, processingRouter, connectedClientsStore, processingTimeout),
                     ClientEndpoint.name(ctx))

    val incomingMessages: Sink[Message, NotUsed] = Flow[Message]
      .map {
        case TextMessage.Strict(jsContent) => Some(IncomingMessage(jsContent))

        case ts: TextMessage.Streamed =>
          ts.textStream.runWith(Sink.ignore)
          None

        case br: BinaryMessage =>
          br.dataStream.runWith(Sink.ignore)
          None
      }
      .collect {
        case Some(message: IncomingMessage) => message
      }
      .to(Sink.actorRef[IncomingMessage](clientEndpoint, PoisonPill))

    val outgoingMessages: Source[Message, NotUsed] = Source
      .actorRef[OutgoingMessage](BUFFER_SIZE, OverflowStrategy.backpressure)
      .mapMaterializedValue { socket =>
        clientEndpoint ! Attach(socket)
        NotUsed
      }
      .map {
        case OutgoingMessage(jsContent) => TextMessage(jsContent)
      }

    Flow.fromSinkAndSource(incomingMessages, outgoingMessages)
  }
}

object WebSocketHandler {
  private val BUFFER_SIZE: Int = 10
} 
开发者ID:lymr,项目名称:fun-chat,代码行数:57,代码来源:WebSocketHandler.scala

示例2: printMessage

//设置package包名称以及导入依赖的类
package net.ruippeixotog.scalafbp.ws

import akka.event.slf4j.SLF4JLogging
import akka.http.scaladsl.model.ws.{ BinaryMessage, Message, TextMessage }
import akka.stream.scaladsl.Flow

trait WsUtils extends SLF4JLogging {

  private[this] def printMessage(msg: Message): String = msg match {
    case TextMessage.Strict(text) => text
    case _: TextMessage.Streamed => "(streamed text message)"
    case _: BinaryMessage => "(binary message)"
  }

  def logWsMessages(id: String)(handler: Flow[Message, Message, Any]) = {
    Flow[Message]
      .map { msg => log.debug(s"[$id] IN : ${printMessage(msg)}"); msg }
      .via(handler)
      .map { msg => log.debug(s"[$id] OUT: ${printMessage(msg)}"); msg }
  }
} 
开发者ID:ruippeixotog,项目名称:scalafbp,代码行数:22,代码来源:WsUtils.scala

示例3: ShakespeareRoute

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

import akka.http.scaladsl.model._
import akka.http.scaladsl.server.Directives._
import akka.stream._
import akka.stream.scaladsl._
import akka.{ NotUsed }
import akka.actor.ActorSystem
import scala.concurrent.duration._
import akka.http.scaladsl.marshalling.{Marshaller, ToResponseMarshaller}
import akka.http.scaladsl.model.HttpEntity.ChunkStreamPart
import spray.json.DefaultJsonProtocol._
import models.Character
import repositories.ShakespeareRepository
import akka.http.scaladsl.model.ws.{ TextMessage, Message }
import spray.json._

class ShakespeareRoute(workingDirectory: String)(implicit
  system: ActorSystem,
  materializer: ActorMaterializer
) {

  val repository = new ShakespeareRepository()

  val source: Source[Character, NotUsed] = Source(repository.romeoEtJuliette)
  val romeoEtJulietteIterable = repository.romeoEtJuliette.toIterator

  def toNewLineFlow[A]: Flow[A, String, NotUsed] = Flow[A].map(_.toString + "\n")

  implicit val characterFormat = jsonFormat2(Character)

  implicit val toResponseMarshaller: ToResponseMarshaller[Source[String, Any]] =
    Marshaller.opaque { items =>
      val data = items.map(item => ChunkStreamPart(item))
      HttpResponse(entity = HttpEntity.Chunked(MediaTypes.`application/json`, data))
    }

  def throttler[A](duration: FiniteDuration): Flow[A, A, NotUsed] =
    Flow[A].throttle(1, duration, 1, ThrottleMode.shaping)

  def routes = path("romeoEtJuliette") {
    handleWebSocketMessages(Flow[Message].mapConcat {
      case tm: TextMessage if romeoEtJulietteIterable.hasNext =>
        TextMessage(romeoEtJulietteIterable.next().toJson.toString) :: Nil
      case other =>
        println(other)
        Nil
    })
  } ~
    path("romeoAndJuliette") { get(complete(romeoAndJulietteSource)) } ~
    pathEnd { getFromFile(s"$workingDirectory/theatre.html") }

  private def romeoAndJulietteSource: Source[String, NotUsed] = source
    .map(c => s"${c.name} - ${c.text}")
    .via(toNewLineFlow)
    .via(throttler(0.5.second))

} 
开发者ID:Giovannini,项目名称:hackday-akka-vue,代码行数:59,代码来源:ShakespereRoute.scala

示例4: MessageServer

//设置package包名称以及导入依赖的类
package eu.svez.backpressuredemo.C_websockets

import akka.http.scaladsl.Http
import akka.http.scaladsl.model.ws.Message
import akka.http.scaladsl.server.Directives._
import akka.stream.scaladsl.{Flow, Sink, Source}
import eu.svez.backpressuredemo.StreamDemo
import eu.svez.backpressuredemo.Flows._

object MessageServer extends StreamDemo {

  sinkRate.send(5)

  val sink = Flow[Message]
    .via(valve(sinkRate.get()))
    .via(meter("sinkWS"))
    .to(Sink.ignore)

  val handlerFlow = Flow.fromSinkAndSource(sink, Source.maybe)

  val route = get {
    path("messages") {
      extractUpgradeToWebSocket{ wsUpgrade =>
        complete(wsUpgrade.handleMessages(handlerFlow))
      }
    }
  }

  val host = "0.0.0.0"
  val port = 9090

  Http().bindAndHandle(route, host, port).map { _ =>
    println(s"Websocket server started on $host:$port")
  }

  readRatesFromStdIn()
} 
开发者ID:svezfaz,项目名称:akka-backpressure-scala-central-talk,代码行数:38,代码来源:MessageServer.scala

示例5: route

//设置package包名称以及导入依赖的类
package phu.quang.le.routes

import akka.http.scaladsl.server.Directives
import akka.http.scaladsl.model.ws.{ Message, TextMessage }
import akka.stream.scaladsl.{ Source, Flow }

trait WsRouter extends Directives {
  def route = 
    path("register") {
      parameter('name) {
        name => handleWebSocketMessages(broadcast(name))
      }  
    }
  
  def broadcast(name: String): Flow[Message, Message, Any] = {
    Flow[Message].mapConcat { 
      case tm: TextMessage =>
        TextMessage(Source.single(name + "::") ++ tm.textStream) :: Nil
      case _ =>
        TextMessage(Source.single(name + "::")) :: Nil
    }
  }
} 
开发者ID:p-le,项目名称:manga-batch,代码行数:24,代码来源:WsRouter.scala

示例6: WebSocketHandler

//设置package包名称以及导入依赖的类
package com.ulasakdeniz.hakker.websocket

import akka.actor.ActorRef
import akka.http.scaladsl.model.ws.Message
import akka.stream.FlowShape
import akka.stream.scaladsl.{Broadcast, Flow, GraphDSL, Sink}

class WebSocketHandler {

  def apply(transform: PartialFunction[Message, Message]): Flow[Message, Message, _] =
    flow(transform)

  def apply(transform: PartialFunction[Message, Message],
            actorRef: ActorRef,
            onCompleteMessage: Any): Flow[Message, Message, _] =
    flow(transform, Some(Sink.actorRef(actorRef, onCompleteMessage)))

  def apply(transform: PartialFunction[Message, Message],
            sink: Sink[Message, _]): Flow[Message, Message, _] =
    flow(transform, Some(sink))

  def flow(transform: PartialFunction[Message, Message],
           sinkOpt: Option[Sink[Message, _]] = None): Flow[Message, Message, _] = {

    Flow
      .fromGraph(GraphDSL.create() { implicit builder =>
        import GraphDSL.Implicits._

        val incomingMessage = builder.add(Flow[Message].collect(transform))

        val in = sinkOpt
          .map(sink => {
            val broadcast = builder.add(Broadcast[Message](2))

            val sinkShape = builder.add(sink)

            broadcast.out(0) ~> sinkShape.in
            broadcast.out(1) ~> incomingMessage.in
            broadcast.in
          })
          .getOrElse {
            incomingMessage.in
          }

        FlowShape(in, incomingMessage.out)
      })
      .via(failureHandler)
  }

  private def failureHandler: Flow[Message, Message, _] =
    Flow[Message].recover[Message] {
      case ex: Exception =>
        // TODO: handle
        throw ex
    }
} 
开发者ID:ulasakdeniz,项目名称:hakker,代码行数:57,代码来源:WebSocketHandler.scala

示例7: route

//设置package包名称以及导入依赖的类
package com.knoldus.account

import akka.http.scaladsl.model.ws.{Message, TextMessage}
import akka.http.scaladsl.server.Directives
import akka.stream.scaladsl.{Flow, Sink, Source}


trait WebServer extends Directives {

  var accounts: Map[String, String] = Map.empty

  def route =
    path("register") {
      parameter('name) { name ?
        handleWebSocketMessages(handler(name))
      }
    }

  def handler(name: String): Flow[Message, Message, Any] = {
    Flow[Message].collect {
      case TextMessage.Strict(txt) => txt
    }.via(validateAndRegister(name))
      .map {
        case msg: String => TextMessage.Strict(msg)
      }
  }

  private def validateAndRegister(name: String) = {
    accounts.get(name) match {
      case Some(id) => Flow.fromSinkAndSource(Sink.ignore, Source.single(name + "::You are already registered !!!!"))
      case None => {
        val id = java.util.UUID.randomUUID().toString
        accounts += (name -> id)
        Flow.fromSinkAndSource(Sink.ignore, Source.single(id))
      }
    }
  }
} 
开发者ID:knoldus,项目名称:akka-http-websocket-microservices.g8,代码行数:39,代码来源:WebServer.scala

示例8: AccountWebServerTest

//设置package包名称以及导入依赖的类
package com.knoldus.account

import akka.http.scaladsl.model.headers.{CustomHeader, Upgrade, UpgradeProtocol}
import akka.http.scaladsl.model.ws.{Message, UpgradeToWebSocket}
import akka.http.scaladsl.model.{HttpRequest, HttpResponse, StatusCodes}
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.stream.{FlowShape, Graph}
import org.scalatest.{Matchers, WordSpec}


class AccountWebServerTest extends WordSpec with Matchers with ScalatestRouteTest with WebServer {

  "User" should {
    "be able to create account" in {
      Get("/register?name=john") ~>
        Upgrade(List(UpgradeProtocol("websocket"))) ~> emulateHttpCore ~>
        route ~> check {
        status shouldEqual StatusCodes.SwitchingProtocols
      }
    }
  }

  private def emulateHttpCore(req: HttpRequest): HttpRequest =
    req.header[Upgrade] match {
      case Some(upgrade) if upgrade.hasWebSocket => req.copy(headers = req.headers :+ upgradeToWebsocketHeaderMock)
      case _ => req
    }

  private def upgradeToWebsocketHeaderMock: UpgradeToWebSocket =
    new CustomHeader() with UpgradeToWebSocket {
      override def requestedProtocols = Nil

      override def name = "dummy"

      override def value = "dummy"

      override def renderInRequests = true

      override def renderInResponses = true

      override def handleMessages(handlerFlow: Graph[FlowShape[Message, Message], Any], subprotocol: Option[String]): HttpResponse =
        HttpResponse(StatusCodes.SwitchingProtocols)
    }
} 
开发者ID:knoldus,项目名称:akka-http-websocket-microservices.g8,代码行数:45,代码来源:AccountWebServerTest.scala

示例9: WebServer

//设置package包名称以及导入依赖的类
package com.knoldus.server

import akka.actor.ActorSystem
import akka.http.scaladsl.model.ws.{Message, TextMessage, WebSocketRequest}
import akka.http.scaladsl.server.Directives
import akka.http.scaladsl.{Http, HttpExt}
import akka.stream.scaladsl.{Flow, Sink, Source}


class WebServer(implicit system: ActorSystem) extends Directives {

  var accounts: Map[String, String] = Map.empty
  val http: HttpExt = Http()

  def route =
    path("register") {
      parameter('name) { name ?
        handleWebSocketMessages(handler("ws://localhost:9001/register?name=" + name, name))
      }
    } ~ path("create" / Segment) { id =>
      accounts.values.toList.contains(id) match {
        case false => {
          handleWebSocketMessages(Flow[Message].collect {
            case TextMessage.Strict(txt) => txt
          }.via(Flow.fromSinkAndSource(Sink.ignore, Source.single("You are not registered!!!!!!!!!!!")))
            .map {
              case msg: String => TextMessage.Strict(msg)
            })
        }
        case true => handleWebSocketMessages(http.webSocketClientFlow(WebSocketRequest("ws://localhost:9002/create")))
      }
    }

  def handler(url: String, name: String): Flow[Message, Message, Any] = {
    http.webSocketClientFlow(WebSocketRequest(url)).map {
      case TextMessage.Strict(txt) => {
        if (txt contains ("You are already registered")) {
          TextMessage(txt)
        } else {
          accounts += (name -> txt)
          TextMessage(s"You are registered !!!! Use this ${txt} to create order!!")
        }
      }
    }

  }

} 
开发者ID:knoldus,项目名称:akka-http-websocket-microservices.g8,代码行数:49,代码来源:WebServer.scala

示例10: route

//设置package包名称以及导入依赖的类
package com.knoldus.order

import akka.http.scaladsl.model.ws.{Message, TextMessage}
import akka.http.scaladsl.server.Directives
import akka.stream.scaladsl.{Flow, Source}


trait WebServer extends Directives {

  def route =
    path("create") {
        handleWebSocketMessages(handler)
    }

  def handler: Flow[Message, Message, Any] = {
    Flow[Message].mapConcat {
      case tm: TextMessage =>
        TextMessage(Source.single("Your order is created. Order value is ") ++ tm.textStream) :: Nil
    }

  }
} 
开发者ID:knoldus,项目名称:akka-http-websocket-microservices.g8,代码行数:23,代码来源:WebServer.scala

示例11: wsFlow

//设置package包名称以及导入依赖的类
package name.denyago.yasc.http

import akka.http.scaladsl.model._
import akka.http.scaladsl.model.ws.Message
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import akka.stream.scaladsl.Flow


trait Router {
  def wsFlow: Flow[Message, Message, Any]

  val routes: Route =
    path("status") {
      get {
        complete(HttpEntity(ContentTypes.`application/json`, "{\"status\":\"OK\"}"))
      }
    } ~
      path("ws")(handleWebSocketMessages(wsFlow))
} 
开发者ID:denyago,项目名称:yet-another-simple-chat,代码行数:21,代码来源:Router.scala

示例12: chatRoom

//设置package包名称以及导入依赖的类
package name.denyago.yasc.http.websocket

import akka.NotUsed
import akka.actor.{ActorRef, ActorSystem, PoisonPill, Props}
import akka.http.scaladsl.model.ws.{Message, TextMessage}
import akka.stream.scaladsl.{Flow, Sink, Source}
import akka.stream.{ActorMaterializer, OverflowStrategy}
import name.denyago.yasc.chat.ConnectedUser
import name.denyago.yasc.chat.events.{ConnectionEstablished, MessagePosted, MessageReceived}


trait WsFlow {
  implicit val webSocketSys = ActorSystem("websocket-system")
  implicit val webSocketMat = ActorMaterializer()

  def chatRoom: ActorRef

  def wsFlow: Flow[Message, Message, NotUsed] = {
    val userActor = webSocketSys.actorOf(Props(new ConnectedUser(chatRoom)))

    val incomingMessages: Sink[Message, NotUsed] =
      Flow[Message].map {
        case TextMessage.Strict(text) => MessageReceived(text)
      }.to(Sink.actorRef[MessageReceived](userActor, PoisonPill))

    val outgoingMessages: Source[Message, NotUsed] =
      Source.actorRef[MessagePosted](10, OverflowStrategy.fail)
          .mapMaterializedValue { outgoingActor =>
            userActor ! ConnectionEstablished(outgoingActor)
            NotUsed
          }
        .map(
          (outgoingMessage: MessagePosted) => TextMessage(outgoingMessage.text))

    Flow.fromSinkAndSource(incomingMessages, outgoingMessages)
  }
} 
开发者ID:denyago,项目名称:yet-another-simple-chat,代码行数:38,代码来源:WsFlow.scala

示例13: SubscriptionService

//设置package包名称以及导入依赖的类
package me.mmcoulombe.aad.services

import akka.http.scaladsl.model.ws.{Message, TextMessage}
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Flow
import me.mmcoulombe.aad.EventManager
import me.mmcoulombe.aad.descriptor.SubscriptionServiceDescriptor
import me.mmcoulombe.add.json.JsonSupport
import play.api.libs.json.Json

import scala.concurrent.{ExecutionContext, Future}
import scala.util.Failure

class SubscriptionService(eventManager: EventManager)
                         (implicit ec: ExecutionContext, materialize: ActorMaterializer) extends SubscriptionServiceDescriptor with JsonSupport {
  def manageEvent(): Flow[Message, Message, Any] =
    Flow[Message]
      .mapAsync(1) {
        case TextMessage.Strict(msg) => Future.successful(msg)
        case streamed: TextMessage.Streamed => streamed.textStream.runFold("")(_ + _)
      }.via(eventManager.flow)
      .map(msg => TextMessage.Strict(Json.stringify(Json.toJson(msg))))

  def reportErrorsFlow[T]: Flow[T, T, Any] =
    Flow[T]
      .watchTermination()((_, f) => f.onComplete {
        case Failure(err) =>
          println(s"WS stream failed : $err")
        case _ =>
      })
} 
开发者ID:mmcoulombe,项目名称:poc-aad,代码行数:32,代码来源:SubscriptionService.scala

示例14: NetworkRoute

//设置package包名称以及导入依赖的类
package de.tu_berlin.formic.example

import akka.NotUsed
import akka.actor.ActorSystem
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.model.ws.Message
import akka.http.scaladsl.server
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Flow


class NetworkRoute(implicit val actorSystem: ActorSystem) {

  val authenticator = UniqueUsernameAuthenticator(actorSystem)

  def route(newUserMethod: (String) => Flow[Message, Message, NotUsed])(implicit actorSystem: ActorSystem, materializer: ActorMaterializer): server.Route = {
    path("formic") {
      authenticateBasic[String]("FormicRealm", (creds) => authenticator.authenticate(creds)) {
        identifier =>
          get {
            handleWebSocketMessages(newUserMethod(identifier))
          }
      }
    } ~
    pathEndOrSingleSlash {
      redirect("/index", StatusCodes.PermanentRedirect)
    } ~
    path("index") {
      getFromResource("index.html")
    } ~
    path("battleship") {
      getFromResource("battleship.html")
    } ~
      getFromResourceDirectory("") //this route is needed to serve the JavaScript files to clients
    //seeing too many "New connection accepted" and "got -1 from read"? See https://groups.google.com/forum/#!topic/akka-user/ai5dOX8Cuco
  }
} 
开发者ID:rbraeunlich,项目名称:formic,代码行数:39,代码来源:NetworkRoute.scala

示例15: WebSockets

//设置package包名称以及导入依赖的类
package mm4s.api

import akka.actor.{ActorRef, ActorSystem}
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.ws.{Message, TextMessage, WebSocketRequest}
import akka.stream.scaladsl.{Flow, Keep, Sink, Source}
import akka.stream.{ActorMaterializer, OverflowStrategy}
import mm4s.api.WebSocketModels.WebSocketMessage
import spray.json._

import scala.collection.immutable



object WebSockets {
  case object SocketClosed

  def flow(token: String, host: String, port: Int = 8080)(implicit system: ActorSystem) = {
    Http().webSocketClientFlow(WebSocketRequest(s"ws://$host:$port$mmapi/websocket", extraHeaders = immutable.Seq(auth(token))))
  }

  def source()(implicit system: ActorSystem) = {
    Source.queue[TextMessage](10, OverflowStrategy.fail)
  }

  def toActor(ref: ActorRef)(implicit system: ActorSystem) = {
    Sink.actorRef(ref, SocketClosed)
  }

  def connect(ref: ActorRef, token: String, host: String, port: Int = 8080)(implicit system: ActorSystem, mat: ActorMaterializer) = {
    import WebSocketProtocol._

    source()
    .viaMat(flow(token, host, port))(Keep.both)
    .via(Flow[Message].collect { case m: TextMessage.Strict => m.text })
    .map(s => s.parseJson.convertTo[WebSocketMessage])
    .toMat(toActor(ref))(Keep.both)
    .run()
  }
}


object WebSocketModels {
  case class WebSocketMessage(team_id: String, channel_id: String, user_id: String, action: Action, props: WsmProps)
  case class WsmPost(id: String, create_at: Long, user_id: String, channel_id: String, message: String, `type`: String, hashtags: String, filenames: Seq[String])
  case class WsmProps(channel_type: Option[String], otherFile: Option[String], post: Option[String]) {
    import WebSocketProtocol.wsmPostFormat
    def posted: Option[WsmPost] = post.map(_.parseJson.convertTo[WsmPost])
  }
}


object WebSocketProtocol extends DefaultJsonProtocol {
  import ActionProtocol._
  import WebSocketModels._

  implicit val wsmPostFormat: RootJsonFormat[WsmPost] = jsonFormat8(WsmPost)
  implicit val wsmPropsFormat: RootJsonFormat[WsmProps] = jsonFormat3(WsmProps)
  implicit val wsmFormat: RootJsonFormat[WebSocketMessage] = jsonFormat5(WebSocketMessage)
} 
开发者ID:jw3,项目名称:mm4s,代码行数:61,代码来源:WebSockets.scala


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