Last active
April 24, 2024 13:37
-
-
Save koenkarsten/e4ed82c7a8cb1d03cf0d to your computer and use it in GitHub Desktop.
A simple TCP Socket Server made with Scala + Akka IO
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
name := "Server" | |
organization := "example.server" | |
version := "1.0" | |
scalaVersion := "2.11.7" | |
libraryDependencies ++= { | |
Seq( | |
"com.typesafe.akka" %% "akka-http-core-experimental" % "2.0.2" | |
) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.net.InetSocketAddress | |
import akka.actor.{ActorSystem, Props, Actor} | |
import akka.io.{Tcp, IO} | |
import akka.io.Tcp._ | |
import akka.util.ByteString | |
class TCPConnectionManager(address: String, port: Int) extends Actor { | |
import context.system | |
IO(Tcp) ! Bind(self, new InetSocketAddress(address, port)) | |
override def receive: Receive = { | |
case Bound(local) => | |
println(s"Server started on $local") | |
case Connected(remote, local) => | |
val handler = context.actorOf(Props[TCPConnectionHandler]) | |
println(s"New connnection: $local -> $remote") | |
sender() ! Register(handler) | |
} | |
} | |
class TCPConnectionHandler extends Actor { | |
override def receive: Actor.Receive = { | |
case Received(data) => | |
val decoded = data.utf8String | |
sender() ! Write(ByteString(s"You told us: $decoded")) | |
case message: ConnectionClosed => | |
println("Connection has been closed") | |
context stop self | |
} | |
} | |
object Server extends App { | |
val system = ActorSystem() | |
val tcpserver = system.actorOf(Props(classOf[TCPConnectionManager], "localhost", 8080)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Saved me lots of time. Thanks a ton!