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


Scala WebSocket类代码示例

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


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

示例1: Users

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

import javax.inject._

import actors.{WebSockets, UsersArea}
import akka.actor._
import play.api.Play.current
import play.api.data.Form
import play.api.data.Forms._
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.libs.json.JsValue
import play.api.mvc.{Action, Controller, WebSocket}

import scala.concurrent.Future

@Singleton
class Users @Inject()(val messagesApi: MessagesApi, system: ActorSystem) extends Controller with I18nSupport {
  val User = "user"

  val nickForm = Form(single("nickname" -> nonEmptyText))

  def index = Action { implicit request =>
    request.session.get(User).map { user =>
      Redirect(routes.Users.chat()).flashing("info" -> s"Redirected to chat as $user user")
    }.getOrElse(Ok(views.html.index(nickForm)))
  }

  def name = Action { implicit request =>
    nickForm.bindFromRequest.fold(
      formWithErrors => {
        BadRequest(views.html.index(formWithErrors))
      },
      nickname => {
        Redirect(routes.Users.chat())
          .withSession(request.session + (User -> nickname))
      }
    )
  }

  def leave = Action { implicit request =>
    Redirect(routes.Users.index()).withNewSession.flashing("success" -> "See you soon!")
  }

  def chat = Action { implicit request =>
    request.session.get(User).map { user =>
      Ok(views.html.chat(user))
    }.getOrElse(Redirect(routes.Users.index()))
  }

  def socket = WebSocket.tryAcceptWithActor[JsValue, JsValue] { implicit request =>
    Future.successful(request.session.get(User) match {
      case None => Left(Forbidden)
      case Some(uid) => Right(WebSockets.props(uid))
    })
  }
} 
开发者ID:maltiyadav,项目名称:messaging-system-websockets,代码行数:57,代码来源:Users.scala

示例2: Chat

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

import javax.inject._

import actors.{UserSocket, ChatRoom}
import akka.actor._
import play.api.Play.current
import play.api.data.Form
import play.api.data.Forms._
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.libs.json.JsValue
import play.api.mvc.{Action, Controller, WebSocket}

import scala.concurrent.Future

@Singleton
class Chat @Inject()(val messagesApi: MessagesApi, system: ActorSystem) extends Controller with I18nSupport {
  val User = "user"

  val chatRoom = system.actorOf(Props[ChatRoom], "chat-room")

  val nickForm = Form(single("nickname" -> nonEmptyText))

  def index = Action { implicit request =>
    request.session.get(User).map { user =>
      Redirect(routes.Chat.chat()).flashing("info" -> s"Redirected to chat as $user user")
    }.getOrElse(Ok(views.html.index(nickForm)))
  }

  def nickname = Action { implicit request =>
    nickForm.bindFromRequest.fold(
      formWithErrors => {
        BadRequest(views.html.index(formWithErrors))
      },
      nickname => {
        Redirect(routes.Chat.chat())
          .withSession(request.session + (User -> nickname))
      }
    )
  }

  def leave = Action { implicit request =>
    Redirect(routes.Chat.index()).withNewSession.flashing("success" -> "See you soon!")
  }

  def chat = Action { implicit request =>
    request.session.get(User).map { user =>
      Ok(views.html.chat(user))
    }.getOrElse(Redirect(routes.Chat.index()))
  }

  def socket = WebSocket.tryAcceptWithActor[JsValue, JsValue] { implicit request =>
    Future.successful(request.session.get(User) match {
      case None => Left(Forbidden)
      case Some(uid) => Right(UserSocket.props(uid))
    })
  }
} 
开发者ID:onegrx,项目名称:playakkachat,代码行数:59,代码来源:Chat.scala

示例3: Application

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

import scala.Left
import scala.Right
import scala.concurrent.Future
import actors.UserActor
import play.api.Logger
import play.api.Play.current
import play.api.libs.json.JsValue
import play.api.mvc.Action
import play.api.mvc.Controller
import play.api.mvc.WebSocket

object Application extends Controller {
  val UID = "uid"
  var counter = 0;

  def index = Action { implicit request =>
    {
      val uid = request.session.get(UID).getOrElse {
        counter += 1
        counter.toString
      }
      Ok(views.html.index(uid)).withSession {
        Logger.debug("creation uid " + uid)
        request.session + (UID -> uid)
      }
    }
  }

  
  def ws = WebSocket.tryAcceptWithActor[JsValue, JsValue] { implicit request =>
    Future.successful(request.session.get(UID) match {
      case None => Left(Forbidden)
      case Some(uid) => Right(UserActor.props(uid))
    })
  }

} 
开发者ID:OCervantes,项目名称:websocket-play,代码行数:40,代码来源:Application.scala

示例4: Application

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

import actors.UserActor
import play.api.Play.current
import play.api.libs.json.JsValue
import play.api.mvc.{Action, Controller, WebSocket}

import scala.concurrent.Future

object Application extends Controller {
  val Nick = "nickname"
  val Address = "address"
  val Msg = "msg"

  def index = Action { implicit request =>
    Ok(views.html.index.apply).withNewSession
  }

  def chat = Action { implicit request =>
    Ok(views.html.chat(
      request.queryString(Nick).head, request.queryString(Address).head)
    ).withSession(request.session + (Nick -> request.queryString(Nick).head))
  }

  def ws = WebSocket.tryAcceptWithActor[JsValue, JsValue] { implicit request =>
    Future.successful(request.session.get(Nick) match {
      case None => Left(Forbidden)
      case Some(nick) => Right(UserActor.props(nick))
    })
  }

}
 
开发者ID:baydindima,项目名称:ScalaChat,代码行数:33,代码来源:Application.scala

示例5: HomeController

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

import javax.inject.Inject

import actors.SearchActor
import akka.actor.ActorSystem
import akka.stream.Materializer
import models.daos.{GameDAO, GenreDAO, OfferDAO, PlatformDAO}
import models.entities.{Game, Genre, Offer}
import play.api.libs.json.{JsValue, Json, Writes}
import play.api.libs.streams.ActorFlow
import play.api.mvc.{Action, AnyContent, Controller, WebSocket}

import scala.collection.mutable
import scala.concurrent.ExecutionContext

class HomeController @Inject()(gameDAO: GameDAO,
                               offerDAO: OfferDAO,
                               platformDAO: PlatformDAO,
                               genreDAO: GenreDAO)(implicit ec:ExecutionContext, system: ActorSystem, mat:Materializer) extends Controller {


  def index() = Action.async { implicit request =>
    for {
      tuplesPlatformCount <- platformDAO.allPlatformsOffersWithCount
      tuplesGenreCount <- genreDAO.allGenresWithCount
      tuplesOfferGamePlatform <- offerDAO.actualOffers  //obtencion de las ofertas
      tuplesBestOfferGamePlatform <- offerDAO.lastGamesWithOffers
      gamesWithGenres <- genreDAO.allGamesWithGenres()
    } yield Ok(views.html.home(
      title = "Inicio",
      tuplesPlatformCount = tuplesPlatformCount.toList,
      tuplesGenreCount = tuplesGenreCount.toList,
      tuplesOfferGamePlatform = tuplesOfferGamePlatform.toList,
      tuplesBestOfferGamePlatform = tuplesBestOfferGamePlatform.toList,
      hashTableGenres = gamesWithGenres.groupBy(_._1).map{case (k, v) => (k, v.map(_._2).toList)}
    ))
  }

  def search() = Action(parse.urlFormEncoded) { request =>
    Redirect(routes.ResultController.index(request.body.get("search").head.head))
  }

  // JsValue ~ JSON
  def socket = WebSocket.accept[JsValue, JsValue] { request =>
    ActorFlow.actorRef(out => SearchActor.props(out,gameDAO))
  }
} 
开发者ID:CC5111,项目名称:isThereAnyOffer,代码行数:49,代码来源:HomeController.scala

示例6: Napucon2016Controller

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

import javax.inject.{Inject, Singleton}

import akka.actor.{Actor, ActorLogging, ActorRef, ActorSystem, Props}
import akka.stream.Materializer
import play.api.Configuration
import play.api.libs.streams.ActorFlow
import play.api.libs.ws.WSClient
import play.api.mvc.{Controller, WebSocket}

import scala.concurrent.ExecutionContext.Implicits.global


@Singleton
class Napucon2016Controller @Inject() (implicit config: Configuration,
                                       wsClient: WSClient,
                                       system: ActorSystem,
                                       materializer: Materializer) extends Controller {

  private val apiKey = config.getString("weather.api.key")
    .getOrElse(throw new IllegalStateException("No weather.api.key is set."))

  def ws: WebSocket = WebSocket.accept[String, String] { request =>
    ActorFlow.actorRef(out => WeatherActor.props(apiKey, wsClient, out))
  }
}

object WeatherActor {
  def props(apiKey: String, wsClient: WSClient, out: ActorRef): Props =
    Props(new WeatherActor(apiKey, wsClient, out))
}

class WeatherActor(val apiKey: String,
                   val wsClient: WSClient,
                   val out: ActorRef) extends Actor
                                         with ActorLogging {

  private final val LocationPattern = """([^,]+),([^,]+)""".r

  override def receive: Receive = {
    case msg: String => msg match {
      case LocationPattern(city, country) =>
        wsClient.url(s"http://api.openweathermap.org/data/2.5/weather?q=$city,$country&appid=$apiKey")
                .get()
                .map { response =>
                  out ! response.body
                }

      case _ =>
        sys.error("Unknown message") // replace it with proper response to the user.

    }
  }
} 
开发者ID:Kevin-Lee,项目名称:napucon2016-weather-app,代码行数:56,代码来源:Napucon2016Controller.scala

示例7: ChatController

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

import javax.inject.Inject

import akka.actor._
import akka.stream._
import akka.stream.scaladsl.{ Flow, Keep }
import domains.chat.ChatMessage
import play.api.libs.json.JsValue
import play.api.libs.streams.ActorFlow
import play.api.mvc.WebSocket
import services.chat.ChatService


class ChatController @Inject()(
    implicit val system: ActorSystem,
    implicit val materializer: Materializer,
    streamChatService: ChatService
) {

  def start(roomId: String) = WebSocket.accept[JsValue, JsValue] { request =>


    val userName = request.queryString("user_name").headOption.getOrElse("anon")

    val userInput: Flow[JsValue, ChatMessage, _] = ActorFlow.actorRef[JsValue, ChatMessage](out => ChatRequestActor.props(out, userName))
    val room = streamChatService.start(roomId, userName)
    val userOutPut: Flow[ChatMessage, JsValue, _] = ActorFlow.actorRef[ChatMessage, JsValue](out => ChatResponseActor.props(out,userName))

    userInput.viaMat(room.bus)(Keep.right).viaMat(userOutPut)(Keep.right)
  }
} 
开发者ID:cm-wada-yusuke,项目名称:chatserver-play-websocket-akka-stream,代码行数:33,代码来源:ChatController.scala

示例8: ChatController

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

import models.{User, ChatRoom}
import play.api.data._
import play.api.data.Forms._
import play.api.libs.EventSource
import play.api.libs.iteratee.{Enumeratee, Concurrent}
import play.api.libs.json.JsValue
import play.api.mvc.{WebSocket, Action, Controller}
import play.api.libs.concurrent.Execution.Implicits._

object ChatController extends Controller {

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

  
  def chatWS(username: String) = WebSocket.tryAccept[JsValue] { request  =>

    ChatRoom.join(username).map{ io =>
      Right(io)
    }.recover{ case e => Left(Ok(e))}
  }

  def chatSSE(username: String) = Action.async { request =>
    ChatRoom.join(username).map{ io =>
      Ok.feed(io._2
        &> Concurrent.buffer(50)
        &> Enumeratee.onIterateeDone{ () =>
          play.Logger.info(request.remoteAddress + " - SSE disconnected")
        }
        &> EventSource()).as("text/event-stream")
    }.recover{ case e => BadRequest(e)}
  }

  val talkForm = Form(
    tuple(
      "username" -> nonEmptyText,
      "msg" -> text
    )
  )

  def talk = Action{ implicit request =>
    talkForm.bindFromRequest.fold(
      error => BadRequest,
      value => {
        ChatRoom.talk(value._1, value._2)
        Ok
      }
    )
  }

} 
开发者ID:gurghet,项目名称:rota-scalajs2,代码行数:55,代码来源:ChatController.scala

示例9: MyWebSocket

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

import de.htwg.se.setGame.controller.{NewGame, StartGame, UpdateGame}
import play.api.Logger
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.iteratee.{Concurrent, Iteratee}
import play.api.mvc.WebSocket
import scala.swing.Reactor


class MyWebSocket(private val manager: GameManager) extends Reactor {
  def get: WebSocket = WebSocket.using[String] { request =>
    val session = new SessionHandler(request.session)
    val controller = manager.get(session.getSessionId)
    val in = Iteratee.foreach[String](_ => {}).map { _ =>
      Logger.debug(MyWebSocket.Disconnect.format(session.getSessionId))
    }
    val (out, channel) = Concurrent.broadcast[String]
    Logger.debug(MyWebSocket.Connected.format(session.getSessionId))
    listenTo(controller.getController)

    reactions += {
      case e: NewGame =>
        Logger.debug(MyWebSocket.EventNewGame.format(session.getSessionId))
        channel.push(e.getClass.getName)
      case e: StartGame =>
        Logger.debug(MyWebSocket.EventStartGame.format(session.getSessionId))
        channel.push(e.getClass.getName)
      case e: UpdateGame =>
        Logger.debug(MyWebSocket.EventUpdateGame.format(session.getSessionId))
        channel.push(e.getClass.getName)
    }

    (in, out)
  }
}

object MyWebSocket {
  val Disconnect = "%s - disconnect from websocket"
  val Connected = "%s - connected to websocket"
  val EventNewGame = "%s - websocket received 'NewGame' event"
  val EventStartGame = "%s - websocket received 'StartGame' event"
  val EventUpdateGame = "%s - websocket received 'UpdateGame' event"
} 
开发者ID:phaldan,项目名称:htwg-set-game-scala-wui,代码行数:45,代码来源:MyWebSocket.scala

示例10: SnakeController

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

import java.util.UUID
import javax.inject.Inject

import actors.{SnakeMasterActor, SnakeSocketActor}
import akka.actor.{ActorSystem, Props}
import akka.stream.Materializer
import play.api.libs.streams.ActorFlow
import play.api.mvc.{Controller, WebSocket}
import shared._

class SnakeController @Inject()(
  actorSystem: ActorSystem,
  materializer: Materializer
) extends Controller {

  import models.Formats._

  lazy val master = actorSystem.actorOf(Props(new SnakeMasterActor()))

  def ws() = WebSocket.accept[Direction, WorldState] { rs =>
    val clientId = UUID.randomUUID()
    ActorFlow.actorRef(out => Props(new SnakeSocketActor(out, master, clientId)))(actorSystem, materializer)
  }

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

示例11: MathStringEvaluatorController

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

import javax.inject.Singleton

import akka.actor.{ActorSystem, Props}
import akka.stream.Materializer
import com.google.inject.Inject
import dao.ExpressionHistoryDAO
import eval.MathStringEvaluator
import play.api.Configuration
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json.{JsError, JsSuccess, JsValue, Json}
import play.api.libs.streams.ActorFlow
import play.api.mvc.{Action, Controller, WebSocket}

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


@Singleton
class MathStringEvaluatorController @Inject()(implicit evaluator: MathStringEvaluator, historyDAO: ExpressionHistoryDAO, actorSystem: ActorSystem, materializer: Materializer, configuration: Configuration) extends Controller {
  private case class Expression(expression: String)

  private implicit val expressionReads = Json.reads[Expression]

  def index = Action { implicit request =>
    Ok(views.html.index(configuration.getBoolean("application.sslmode").get))
  }

  def evaluateExpression = Action.async(parse.json) { jsResult =>
    jsResult.body.validate[Expression] match {
      case JsSuccess(Expression(expression), _) =>
        evaluator.evaluateExpression(expression) match {
          case Success(result) =>
            historyDAO.insertExpression(expression, result).map { newExpressionHistory =>
              actorSystem.eventStream.publish(NewHistory(newExpressionHistory))
              Accepted
            }
          case Failure(ex) =>
            Future.successful(BadRequest(Json.obj("error" -> ex.getLocalizedMessage)))
        }
      case JsError(errors) =>
        Future.successful(BadRequest(JsError.toJson(errors)))
    }
  }

  def socket = WebSocket.accept[JsValue, JsValue] { request =>
    ActorFlow.actorRef(out => Props(new WebSocketActor(out, historyDAO.getHistory)))
  }
} 
开发者ID:cowboygneox,项目名称:its-a-bunny,代码行数:51,代码来源:MathStringEvaluatorController.scala

示例12: 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

示例13: WebSocketController

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

import javax.inject.Singleton

import actors.{ActorManager, WebSocketActor}
import akka.actor.{ActorSystem, Props}
import akka.stream.Materializer
import com.google.inject.Inject
import play.api.Configuration
import play.api.libs.json.JsValue
import play.api.libs.streams.ActorFlow
import play.api.mvc.{Action, Controller, WebSocket}
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}

import scala.concurrent.ExecutionContext


@Singleton
class WebSocketController @Inject() (val reactiveMongoApi: ReactiveMongoApi)
                                    (implicit executionContext: ExecutionContext,
                                     configuration: Configuration,
                                     system: ActorSystem,
                                     materializer: Materializer)
  extends Controller with MongoController with ReactiveMongoComponents  {

  lazy final val actorManager = system.actorOf(Props[ActorManager],"actor-manager")

  def socket = WebSocket.accept[JsValue,JsValue] { request =>
    //request.session.get(Id).map { id =>
      ActorFlow.actorRef(out => WebSocketActor.props(actorManager,out,"10"))
    //}.getOrElse(throw new Exception("connection error"))
  }

  def index = Action { implicit request =>
    Ok(views.html.websocket("test"))
  }

} 
开发者ID:tictactoki,项目名称:Immutaskable,代码行数:39,代码来源:WebSocketController.scala

示例14: Chat

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

import actors.{Chatroom, User}
import akka.actor.{ActorRef, ActorSystem}
import akka.stream.Materializer
import play.api.libs.json.JsValue
import play.api.libs.streams.ActorFlow
import play.api.mvc.{Action, Controller, WebSocket}


class Chat(implicit actorSystem: ActorSystem, materializer: Materializer)
    extends Controller {

  // long-lived chatroom
  private val chatRoom: ActorRef = actorSystem.actorOf(Chatroom.props)

  def index = Action { implicit req =>
    Ok(views.html.index())
  }

  def chat = WebSocket.accept[JsValue, JsValue] { _ =>
    // instantiate a User actor and pass it the chatroom
    ActorFlow.actorRef(out => User.props(chatRoom, out))
  }

} 
开发者ID:lloydmeta,项目名称:play-chatroom,代码行数:27,代码来源:Chat.scala

示例15: Application

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

import play.api.libs.json.JsValue
import play.api.Logger
import play.api.mvc.WebSocket.FrameFormatter
import play.api.mvc.{ Action, Controller, WebSocket }
import play.api.Play.current

import lifelines.models.messages.{ Input, Output }

class Application extends Controller {

  def index = Action { req =>
    // val wsUri = routes.Application.create.webSocketURL(req)
    val protocol = if (req.secure) "wss" else "ws"
    val wsUri = s"""${protocol}://${req.host}/create"""
    Ok(views.html.index(wsUri))
  }

  implicit val inEventFrameFormatter = FrameFormatter.jsonFrame[Input]
  implicit val outEventFrameFormatter = FrameFormatter.jsonFrame[Output]

  def create = WebSocket.acceptWithActor[Input, Output] { request => out =>
    val fast = request.getQueryString("fast") == Some("true")
    lifelines.actors.GameActor.props(out, fast)
  }

} 
开发者ID:dohzya,项目名称:lifelines,代码行数:30,代码来源:Application.scala


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