您如何更改此Akka Streams示例以获取物化值Future [ServerBinding]?

时间:2016-03-02 19:58:01

标签: scala akka akka-stream

http://doc.akka.io/docs/akka/2.4.2/scala/stream/stream-io.html的第二个例子如下。我添加了#include<stdio.h> #include<stdlib.h> #include<string.h> #define BUFSIZE 128 char** read( int *pn ); int isSorted( char *str ); char** sortedArr( char **str, int n, int *m ); void print( char **str, int n ); void freeArr( char **str, int n ); void freeArr( char **str, int n ) { if ( !str ) return; int i; for ( i = 0; i < n; i++ ) { free(str[i]); } free(str); } int main() { char **arr = NULL; char **sortArr = NULL; int n = 0, m = 0; arr = read(&n); print(arr, n); printf("\nSorted: \n"); sortArr = sortedArr(arr,n,&m); print(sortArr, m); freeArr(sortArr, m); freeArr(arr, n); return 0; } &amp;的定义host

port

如何更改示例以便获取 val host = "localhost" val port = 4444 val connections: Source[IncomingConnection, Future[ServerBinding]] = Tcp().bind(host, port) connections runForeach { (connection: IncomingConnection) => println(s"New connection from: ${connection.remoteAddress}") val echo = Flow[ByteString] .via(Framing.delimiter( ByteString("\n"), maximumFrameLength = 256, allowTruncation = true)) .map(_.utf8String) .map(_ + "!!!\n") .map(ByteString(_)) connection.handleWith(echo) } ,以便您可以记录成功绑定并处理绑定错误,例如,如果端口是已经在使用了吗?

1 个答案:

答案 0 :(得分:3)

你应该能够摆脱runForeach的便利性,这会隐藏所涉及的Sink的详细信息,而是使用明确的Sink。像这样:

  val host = "localhost"
  val port = 4444
  val connections: Source[IncomingConnection, Future[ServerBinding]] =
    Tcp().bind(host, port)


  val sink = Sink.foreach[IncomingConnection]{ connection =>
    println(s"New connection from: ${connection.remoteAddress}")

    val echo = Flow[ByteString]
      .via(Framing.delimiter(
        ByteString("\n"),
        maximumFrameLength = 256,
        allowTruncation = true))
      .map(_.utf8String)
      .map(_ + "!!!\n")
      .map(ByteString(_))

    connection.handleWith(echo)    
  }

  val serverBinding:Future[ServerBinding] = connections.to(sink).run