Skip to content

Commit

Permalink
first working code
Browse files Browse the repository at this point in the history
  • Loading branch information
Achim Botz committed Mar 4, 2015
1 parent 937e2e9 commit 082ba8b
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/main/scala/org/sandbox/chat/ChatApp.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package org.sandbox.chat

import akka.actor.ActorSystem
import akka.actor.Props

object ChatApp extends App {

val system = ActorSystem("chat-app")

val server =
system.actorOf(Props[ChatServer], "ChuckNorris")

val client1 =
system.actorOf(Props(new ChatClient("client1", server)), "client1")
val client2 =
system.actorOf(Props(new ChatClient("client2", server)), "client2")
val client3 =
system.actorOf(Props(new ChatClient("client3", server)), "client3")

system.shutdown
}
15 changes: 15 additions & 0 deletions src/main/scala/org/sandbox/chat/ChatClient.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package org.sandbox.chat

import akka.actor.Actor
import ChatServer._
import akka.actor.ActorRef

class ChatClient(name: String, chatServer: ActorRef) extends Actor {
def receive: Actor.Receive = {
case Broadcast(msg) =>
println(s"$name: received $msg")
}

chatServer ! Join(name)
chatServer ! Broadcast(s"Hi! I'm $name")
}
26 changes: 26 additions & 0 deletions src/main/scala/org/sandbox/chat/ChatServer.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package org.sandbox.chat

import akka.actor.Actor
import akka.actor.ActorRef
import ChatServer._

class ChatServer extends Actor {
var chatters: Map[ActorRef,String] = Map.empty

override def receive: Actor.Receive = {
case Join(name) => chatters += sender -> name
case Leave => chatters -= sender
case Broadcast(msg) =>
for {
senderName <- chatters.get(sender)
}
chatters.keys foreach (_ ! Broadcast(s"$senderName: $msg"))
}
}

object ChatServer {
sealed trait ChatServerMsg
case class Join(name: String) extends ChatServerMsg
case object Leave
case class Broadcast(msg: String)
}

0 comments on commit 082ba8b

Please sign in to comment.