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

Scala Message类代码示例

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

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



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


示例16: ChatService

//设置package包名称以及导入依赖的类
package co.technius.chatty.server.service

import akka.actor.ActorSystem
import akka.stream.{ FlowShape, Materializer }
import akka.stream.scaladsl._
import akka.stream.actor.{ ActorPublisher, ActorSubscriber }
import akka.http.scaladsl.model.ws.{ BinaryMessage, Message, TextMessage }

class ChatService(implicit system: ActorSystem, mat: Materializer) {
  val roomActor = system.actorOf(RoomActor.props("default"), "defaultroom")
  val roomPub =
    Source
      .fromPublisher[String](ActorPublisher(roomActor))
      .map(msg => TextMessage(Source.single(msg)))

  def flow(name: String): Flow[Message, Message, Any] = {
    val userActor = system.actorOf(UserActor.props(name, roomActor))
    roomActor.tell(InternalProtocol.Join(name), userActor)
    Flow.fromGraph(GraphDSL.create() { implicit b =>
      import GraphDSL.Implicits._

      val userOut = b.add(Source.fromPublisher(ActorPublisher(userActor)))
      val userIn = b.add(Sink.fromSubscriber(ActorSubscriber(userActor)))

      val fromMessage = b.add(msgToStringFlow)
      val toMessage = b.add(Flow[String].map(msg => TextMessage(msg)))

      fromMessage ~> userIn
      userOut ~> toMessage

      FlowShape(fromMessage.in, toMessage.out)
    })
  }

  def msgToStringFlow: Flow[Message, String, Any] = Flow[Message].mapConcat {
    case TextMessage.Strict(msg) => msg :: Nil
    case tm: TextMessage =>
      tm.textStream.runWith(Sink.ignore)
      Nil
    case bm: BinaryMessage =>
      bm.dataStream.runWith(Sink.ignore)
      Nil
  }

} 
开发者ID:Technius,项目名称:chatty,代码行数:46,代码来源:ChatService.scala


示例17: route

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

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("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
    }

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


示例18: Server

//设置package包名称以及导入依赖的类
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.ws.{Message, TextMessage}
import akka.http.scaladsl.model.{ContentTypes, HttpEntity}
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Flow

import scala.io.StdIn


object Server extends App {
  implicit val system = ActorSystem("my-system")
  implicit val materializer = ActorMaterializer()
  // needed for the future flatMap/onComplete in the end
  implicit val executionContext = system.dispatcher

  val echoService: Flow[Message, Message, _] = Flow[Message].map {
    case TextMessage.Strict(txt) => TextMessage("ECHO: " + txt)
    case _ => TextMessage("Message type unsupported")
  }

  val route = get {
    pathEndOrSingleSlash {
      complete("Welcome to akka sample")
    }
  } ~ path("hello") {
    complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, "<h1>Say hello to akka-http</h1>"))
  } ~ path("ws-echo") {
    get {
      handleWebSocketMessages(echoService)
    }
  }


  val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)

  println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
  StdIn.readLine() // let it run until user presses return
  bindingFuture
    .flatMap(_.unbind()) // trigger unbinding from the port
    .onComplete(_ => system.terminate()) // and shutdown when done
} 
开发者ID:kiberStender,项目名称:sprayWebSocket,代码行数:44,代码来源:Server.scala


示例19: ChatRoom

//设置package包名称以及导入依赖的类
package org.ardlema.chat

import akka.NotUsed
import akka.actor.{ ActorSystem, Props }
import akka.http.scaladsl.model.ws.{ Message, TextMessage }
import akka.stream.OverflowStrategy
import akka.stream.scaladsl.{ Flow, Sink, Source }

class ChatRoom(roomId: Int, actorSystem: ActorSystem) {

  private[this] val chatRoomActor = actorSystem.actorOf(Props(classOf[ChatRoomActor], roomId))

  def chatInSink(sender: String) = Sink.actorRef[ChatEvent](chatRoomActor, Left(sender))

  def websocketFlow(user: String): Flow[Message, Message, _] = {
    val in: Sink[Message, NotUsed] =
      Flow[Message]
        .map { case TextMessage.Strict(txt) ? IncomingMessage(user, txt) }
        .to(chatInSink(user))

    // The counter-part which is a source that will create a target ActorRef per
    // materialization where the chatActor will send its messages to.
    // This source will only buffer one element and will fail if the client doesn't read
    // messages fast enough.
    val out: Source[Message, Unit] =
      Source.actorRef[Message](1, OverflowStrategy.fail)
        .mapMaterializedValue(chatRoomActor ! UserJoined(user, _))

    Flow.fromSinkAndSource(in, out)
  }

  def sendMessage(message: ChatMessage): Unit = chatRoomActor ! TextMessage(message.text)
}

object ChatRoom {
  def apply(roomId: Int)(implicit actorSystem: ActorSystem) = new ChatRoom(roomId, actorSystem)
} 
开发者ID:ardlema,项目名称:akka-websockets-examples,代码行数:38,代码来源:ChatRoom.scala


示例20: protocolServerMessageToByteString

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

import akka.http.scaladsl.model.ws.{BinaryMessage, Message}
import akka.stream.scaladsl.Flow
import akka.util.ByteString
import akkaviz.protocol

trait ProtocolSerializationSupport {

  def protocolServerMessageToByteString: Flow[protocol.ApiServerMessage, ByteString, Any] = Flow[protocol.ApiServerMessage].map {
    msg => ByteString(protocol.IO.write(msg))
  }

  def websocketMessageToClientMessage: Flow[Message, protocol.ApiClientMessage, _] = Flow[Message].collect {
    case BinaryMessage.Strict(msg) =>
      protocol.IO.readClient(msg.asByteBuffer)
  }

}

object ProtocolSerializationSupport extends ProtocolSerializationSupport 
开发者ID:blstream,项目名称:akka-viz,代码行数:22,代码来源:ProtocolSerializationSupport.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala PCA类代码示例发布时间:2022-05-23
下一篇:
Scala FilterInputStream类代码示例发布时间: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