Scala PlayFramework 2.3.x如何使用WebSocket向所有客户机和特定客户机广播
更新 这里回答了这个问题@ -- 这里是第一个Play/Scala应用程序,我有点挣扎。我试图实现的是特定渠道(websocket URL)上用户之间的协作。我正试图遵循《Play Framework Essentials》一书中的示例,并尝试适应我的用例。根据客户机的请求,我要么将信息广播给在该频道上讲话的所有客户机,要么只将信息发送回发送初始请求的客户机。广播部分正在工作,但我无法确定如何仅将信息发送回请求的客户端 我的控制器里有Scala PlayFramework 2.3.x如何使用WebSocket向所有客户机和特定客户机广播,scala,playframework,websocket,Scala,Playframework,Websocket,更新 这里回答了这个问题@ -- 这里是第一个Play/Scala应用程序,我有点挣扎。我试图实现的是特定渠道(websocket URL)上用户之间的协作。我正试图遵循《Play Framework Essentials》一书中的示例,并尝试适应我的用例。根据客户机的请求,我要么将信息广播给在该频道上讲话的所有客户机,要么只将信息发送回发送初始请求的客户机。广播部分正在工作,但我无法确定如何仅将信息发送回请求的客户端 我的控制器里有 def ws(channelId: String) = We
def ws(channelId: String) = WebSocket.tryAccept[JsValue] { implicit request =>
getEnumerator(channelId).map { out =>
val in = Iteratee.foreach[JsValue] { jsMsg =>
val id = (jsMsg \ "id").as[String]
// This works and broadcasts that the user has connected
connect(id, request.session.get("email").get)
// Not sure how to return the result of this just to the client of the request
retrieve(id)
}
Right((in, out))
}
}
private def getEnumerator(id: String): Future[Enumerator[JsValue]] = {
(myActor ? GetEnumerator(id)).mapTo[Enumerator[JsValue]]
}
private def connect(id: String, email: String): Unit = {
(myActor ! Connect(id, email))
}
// I have a feeling this is an incorrect return type and I need to return a Future[JsValue]
//and somehow feed that to the enumerator
private def retrieve(id: String): Future[Enumerator[JsValue]] = {
(myActor ? RetrieveInfo(id)).mapTo[Enumerator[JsValue]]
}
在我的演员
class MyActor extends Actor {
var communicationChannels = Map.empty[String, CommunicationChannel]
override def receive: Receive = {
case GetEnumerator(id) => sender() ! getOrCreateCommunicationChannel(id).enumerator
case Connect(id, email) => getOrCreateCommunicationChannel(id).connect(email)
case RetrieveInfo(id) => sender() ! Json.toJson(Info(id, "details for " + id))
}
private def getOrCreateCommunicationChannel(id: String): CommunicationChannel = {
communicationChannels.getOrElse(id, {
val communicationChannel = new CommunicationChannel
communicationChannels += id -> communicationChannel
communicationChannel
})
}
}
object MyActor {
def props: Props = Props[MyActor]
class CommunicationChannel {
val (enumerator, channel) = Concurrent.broadcast[JsValue]
def connect(email: String) = {
channel.push(Json.toJson(Connected(email)))
}
}
}
其中Connect、Connected、Info等只是定义了读写的case类
有人能告诉我,是否可以用这种方法将消息推送到特定的用户,而不是广播给每个人?或者如果我需要以另一种方式实现这一点
还有一种方法可以向除你之外的所有人广播吗
任何帮助都将不胜感激
谢谢