title: Akka Stream, Tcp().bind, handle when the client close the socket
body: <p>I'm quite new in Akka Stream and I'd like to learn how handle a TCP socket for a project of mine. I took this piece of code from the <a href="https://doc.akka.io/docs/akka/current/stream/stream-io.html" rel="nofollow noreferrer">Akka Stream official documentation</a>.</p>
  <pre><code>import akka.stream.scaladsl.Framing
  
  val connections: Source[IncomingConnection, Future[ServerBinding]] =
    Tcp().bind(host, port)
  
  connections.runForeach { connection =&gt;
    println(s&quot;New connection from: ${connection.remoteAddress}&quot;)
  
    val echo = Flow[ByteString]
      .via(Framing.delimiter(ByteString(&quot;\n&quot;), maximumFrameLength = 256, allowTruncation = true))
      .map(_.utf8String)
      .map(_ + &quot;!!!\n&quot;)
      .map(ByteString(_))
  
    connection.handleWith(echo)
  }
  </code></pre>
  <p>If I connect from the terminal using netcat I can see that the Akka Stream TCP socket works as expected. I also found out that If I need to close the connection using an user message, I can use a <code>takeWhile</code> as follow</p>
  <pre><code>import akka.stream.scaladsl.Framing
  
  val connections: Source[IncomingConnection, Future[ServerBinding]] =
    Tcp().bind(host, port)
  
  connections.runForeach { connection =&gt;
    println(s&quot;New connection from: ${connection.remoteAddress}&quot;)
  
    val echo = Flow[ByteString]
      .via(Framing.delimiter(ByteString(&quot;\n&quot;), maximumFrameLength = 256, allowTruncation = true))
      .map(_.utf8String)
      .takeWhile(_.toLowerCase.trim != &quot;exit&quot;)   // &lt; - - - - - - HERE
      .map(_ + &quot;!!!\n&quot;)
      .map(ByteString(_))
  
    connection.handleWith(echo)
  }
  </code></pre>
  <p>What I can't find is how to manage a socket closed by a <code>CMD + C</code> action. Akka Stream use Akka.io to manage the TCP connection internally, so it must send some of its <code>PeerClose</code> messages when the socket is closed. So, my understanding of Akka.io tells me that I should receive a feedback from the socket closing but I can't find how to do that with Akka Stream. Is there a way to manage that ?</p>