简体   繁体   中英

How to send a message from an actor to a Websocket using Play! 2.4?

I'm working with Play! Scala 2.4 and I have a Websocket handled by an actor as following:

object MyWebSocketActor {
  def props(out: ActorRef) = Props(classOf[MyWebSocketActor], out)
}

class MyWebSocketActor @Inject()(out: ActorRef) extends Actor {
  override def receive = {
    case msg: String => out ! ("I received your message: " + msg)
    case _ => out ! "I did not received your message: "
  }
}

class MessagesController extends Controller {

  def openSocket = WebSocket.acceptWithActor[String, String] { request => out =>
    MyWebSocketActor.props(out)
  }
}

It works well but I would like to send to it ( MyWebSocketActor ) some messages from an other actor and I don't manage to make it.

I tried to start it when my application starts with AkkaGuiceSupport like this: bindActor[MyWebSocketActor]("MyWebSocketActor") in order to be able to inject it in an other actor like this: (@Named("MyWebSocketActor") myWebSocketActor: ActorRef) but I get an error since I did not provide an ActorRef when I bind the actor.
The Guice error is:

No implementation for akka.actor.ActorRef was bound.
  while locating akka.actor.ActorRef
    for parameter 0 at controllers.MyWebSocketActor

How can I do that?

The "instance" of MyWebSocketActor is created per connection. So when you want to send a message to it, I guess you want to send message to all instances of MyWebSocketActor (which will transfer those messages to all browsers which have a connection to the websocket)

In that case, you can use the "PubSub" module, have MyWebSocketActor subscribe to a topic, and publish message from your other actors to that.

Here's a activator template which has very good sample regarding this: http://www.lightbend.com/activator/template/akka-clustering?_ga=1.54579683.939088969.1455862030

Here's the document for PubSub module http://doc.akka.io/docs/akka/2.4.2/scala/distributed-pub-sub.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM