Skip to content

Instantly share code, notes, and snippets.

@koenkarsten
Last active April 24, 2024 13:37
Show Gist options
  • Save koenkarsten/e4ed82c7a8cb1d03cf0d to your computer and use it in GitHub Desktop.
Save koenkarsten/e4ed82c7a8cb1d03cf0d to your computer and use it in GitHub Desktop.
A simple TCP Socket Server made with Scala + Akka IO
name := "Server"
organization := "example.server"
version := "1.0"
scalaVersion := "2.11.7"
libraryDependencies ++= {
Seq(
"com.typesafe.akka" %% "akka-http-core-experimental" % "2.0.2"
)
}
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))
}
@ankushs92
Copy link

Saved me lots of time. Thanks a ton!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment