0
我正在学习如何在Akka和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,并添加到HashMap中的任何新连接的ActorRef。我面临的问题是:我在SocketServer类中创建了HashMap,并且我无法简单地在Receive(data)所在的TestHandler类内部访问它。
我是斯卡拉/阿卡的新手,所以如果我问了一些愚蠢的话,请原谅我。
如果答案是很有用的化妆票,如果不评论在 - 至少,不要将其作为空白。 – aravindKrishna