[英]Simple broadcasting socket server in Akka and Scala
我正在学习如何在Akka和Scala中构建简单的广播套接字服务器,到目前为止,我已经完成了下面的工作,它可以处理来自测试客户端的基本套接字连接。 这是代码。
import akka.actor.{Actor,ActorRef,Props,Inbox,ActorSystem}
import akka.io.{IO,Tcp}
import java.net.InetSocketAddress
class TestHandler extends Actor{
import Tcp._
def receive={
case Received(data) =>
println (data received in TestHandler")
// How can I broadcast the message to all connected client here?
case PeerClosed =>
println ("Client closed the connection")
context stop self
}
}
class SocketServer extends Actor{
import Tcp._
import context.system
val connections = new HashMap[String,ActorRef]
IO(Tcp) ! Bind(self,new InetSocketAddress("localhost",8000))
def receive ={
case Connected(remote,local) => //new connection
println("connected")
//create new handler and register it
val handler = context.actorOf(Props[TestHandler])
val connection = sender()
println (s"new connection from $connection")
// Add the new connection to the HashMap
connection ! Tcp.Register(handler)
}
}
object SocketServerTest extends App {
val system = ActorSystem("SocketServer")
val server = system.actorOf(Props[SocketServer],"Myserver")
val inbox = Inbox.create(system)
}
为了进行广播,我将实现一个HashMap并将任何新连接的ActorRef添加到HashMap。 我面临的问题是:我在SocketServer类中创建了HashMap,但我无法简单地在Received(data)所在的TestHandler类内访问它。
我是Scala / Akka的新手,所以如果我问一些愚蠢的事情,请原谅我。
您可以为SocketServer创建伴侣对象。
object SocketServer{
val connections = new HashMap[String,ActorRef]
}
您可以在同一模块中的任何地方使用
SokcetServer.connections
,因为SokcetServer是单例对象。
don't forget to push actorref map under connected(r,l)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.