从出站 Akka TCP 流中检索本地 IP 和端口

Retrieve the local IP and port from an outbound Akka TCP stream

我正在处理一个相当挑剔的协议 (SIP) 的服务器,它需要我的本地 IP 和端口作为 header 结构的一部分。我正在使用 Akka TCP 流,因为它很棒,但我缺少 BSD 套接字的 getsockname 函数的等价物。在 Akka actor-oriented 连接中,连接会发送一条报告本地 IP 和端口的便捷消息,但我找不到从 Akka Streams 版本获取此消息的方法。流直接连接到某个流以进行进一步处理,但没有空间容纳包含连接本地端的 IP 和端口的消息。

val connection = Tcp().outgoingConnection("www.google.com", 80)

val test = List("GET / HTTP/1.1", "Host: www.google.com", "\r\n").map(s ⇒ ByteString(s + "\r\n"))
val res = Source(test).via(connection).runFold(ByteString.empty)( _ ++ _ )

// How do I get the connection details here?
res.onComplete{
  case Success(resp) ⇒ println(resp.utf8String)
  case Failure(f) ⇒ println(f)
}    

有什么想法吗?

这里是 Tcp().outgoingConnection 方法的签名:

def outgoingConnection(host: String, port: Int):
  Flow[ByteString, ByteString, Future[OutgoingConnection]]

物化值是 Future[OutgoingConnection]OutgoingConnection 案例 class 有一个 localAddress 成员。

要访问传出连接的物化值,进而访问本地地址,请使用如下内容:

val (res1, res2) =
  Source(test)
    .viaMat(connection)(Keep.right)
    .toMat(Sink.fold(ByteString.empty)(_ ++ _))(Keep.both)
    .run()

res1 onComplete {
  case Success(OutgoingConnection(_, localAddr)) =>
    println(s"local address: ${localAddr}")
  case Failure(f) =>
    println(f)
}