0

I am learning how to build simple broadcasting socket server in Akka and Scala, I have finished below so far and it can handle basic socket connection from my testing client. Here is the code.

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)



}

In order to do a broadcast I m going to implement a HashMap and add the ActorRef of any new connection to the HashMap. The problem i m facing is :I created the HashMap in SocketServer class and I cannot simply access to it inside the TestHandler class where the Received(data) located.

I am new on Scala / Akka so forgive me if I asked something stupid.

1 Answers1

0

You can create companion object for SocketServer like.

object SocketServer{
val connections = new HashMap[String,ActorRef]
}

you can use SokcetServer.connections any where in same module becoz SokcetServer is singleton object.

don't forget to push actorref map under connected(r,l)
aravindKrishna
  • 440
  • 2
  • 11