2016-07-04 3 views
0

AkkaとScalaでシンプルなブロードキャストソケットサーバーを構築する方法を学んでいます。これまでのところ、テストクライアントから基本的なソケット接続を処理できます。ここにコードがあります。私はHashMapを実装したHashMapへの新しい接続のActorRefを追加するつもり放送を行うために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) 



} 

。私が直面している問題は、SocketServerクラスのHashMapを作成し、TestHandlerクラス内のReceived(データ)が配置されている場所にアクセスできないことです。

私はScala/Akkaの新作です。私が何かばかげて尋ねれば、私を許してください。

+0

答えは有用なものに投票された場合は、で、少なくともコメントでない場合は、空白のままにしないでください。 – aravindKrishna

答えて

0

SocketServerのようなコンパニオンオブジェクトを作成することができます。

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

あなたがSokcetServer.connections任意の場所SokcetServer becoz同じモジュールであるシングルトン オブジェクトを使用することができます。

don't forget to push actorref map under connected(r,l) 
関連する問題