Skip to content

Commit

Permalink
Removed experiments and tidied up example
Browse files Browse the repository at this point in the history
  • Loading branch information
aggenebbisj committed Apr 4, 2016
1 parent c24d8d2 commit b5a12ba
Show file tree
Hide file tree
Showing 6 changed files with 21 additions and 208 deletions.
81 changes: 0 additions & 81 deletions src/main/scala/Demo.scala

This file was deleted.

45 changes: 0 additions & 45 deletions src/main/scala/EchoServer.scala

This file was deleted.

27 changes: 0 additions & 27 deletions src/main/scala/Join.scala

This file was deleted.

15 changes: 0 additions & 15 deletions src/main/scala/Map.scala

This file was deleted.

31 changes: 0 additions & 31 deletions src/main/scala/Maybe.scala

This file was deleted.

30 changes: 21 additions & 9 deletions src/main/scala/Protocol.scala
Original file line number Diff line number Diff line change
@@ -1,37 +1,49 @@
import akka.NotUsed
import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Tcp.{IncomingConnection, ServerBinding}
import akka.stream.scaladsl._
import akka.util.ByteString
import com.typesafe.config.ConfigFactory

import scala.concurrent.Future
import scala.concurrent.{Promise, Future}

/**
* Basis for a unidirectional TCP protocol
*/
object Protocol extends App {

implicit val system = ActorSystem("unidirectional-tcp", ConfigFactory.defaultReference())
implicit val materializer = ActorMaterializer()
import system.dispatcher

val binding: Source[IncomingConnection, Future[ServerBinding]] = Tcp().bind("localhost", 8888)
val binding: Source[IncomingConnection, Future[ServerBinding]] =
Tcp().bind("localhost", 8888)

binding.runForeach { (incomingConnection: IncomingConnection) =>
println(s"New connection from: ${incomingConnection.remoteAddress}")

// Sink can be swapped by f.i. an ActorSubscriber
val targetSink = Sink.foreach[String](e => println("Sink received: " + e))

val completionSource: Source[ByteString, Promise[Option[ByteString]]] =
Source.maybe[ByteString].drop(1) // Discard the element immediately, only used for closing connection

val (closePromise, doneFuture) =
Source.maybe[ByteString]
completionSource
.via(incomingConnection.flow)
.via(incoming)
.toMat(Sink.foreach(println))(Keep.both).run()
.via(protocol)
.toMat(targetSink)(Keep.both) // We keep both, because we use the future to complete the promise
.run()

// How is this promise completed???
// Completing the promise closes the connection
import system.dispatcher // Execution context for promise
closePromise.completeWith(doneFuture.map { _ =>
Some(ByteString.empty)
Some(ByteString.empty) // Dummy element, will be dropped anyway
})
}

// Simple flow mapping ByteStrings to Strings
val incoming: Flow[ByteString, String, _] =
val protocol: Flow[ByteString, String, _] =
Flow[ByteString].map(_.utf8String)

}

0 comments on commit b5a12ba

Please sign in to comment.