Unix Domain Socket

From Wikipedia, A Unix domain socket or IPC socket (inter-process communication socket) is a data communications endpoint for exchanging data between processes executing on the same host operating system. Unix Domain Sockets leverage files and so operating system level access control can be utilized. This is a security advantage over using TCP/UDP where IPC is required without a more complex Transport Layer Security (TLS). Performance also favors Unix Domain Sockets over TCP/UDP given that the Operating System’s network stack is bypassed.

This connector provides an implementation of a Unix Domain Socket with interfaces modelled on the conventional Tcp Akka Streams class. The connector uses JNI and so there are no native dependencies.

Note that Unix Domain Sockets, as the name implies, do not apply to Windows.

Reported issues

Tagged issues at Github

Artifacts

sbt
libraryDependencies += "com.lightbend.akka" %% "akka-stream-alpakka-unix-domain-socket" % "0.20"
Maven
<dependency>
  <groupId>com.lightbend.akka</groupId>
  <artifactId>akka-stream-alpakka-unix-domain-socket_2.12</artifactId>
  <version>0.20</version>
</dependency>
Gradle
dependencies {
  compile group: 'com.lightbend.akka', name: 'akka-stream-alpakka-unix-domain-socket_2.12', version: '0.20'
}

Usage

The binding and connecting APIs are extremely similar to the Tcp Akka Streams class. UnixDomainSocket is generally substitutable for Tcp except that the SocketAddress is different (Unix Domain Sockets requires a java.net.File as opposed to a host and port). Please read the following for details:

Binding to a file

Scala
val binding =
  UnixDomainSocket().bindAndHandle(Flow.fromFunction(identity), file)
Full source at GitHub
Java
final Source<IncomingConnection, CompletionStage<ServerBinding>> connections =
    UnixDomainSocket.get(system).bind(file);
Full source at GitHub

Connecting to a file

Scala
binding.flatMap { connection =>
  val sendBytes = ByteString("Hello")
  val result =
    Source
      .single(sendBytes)
      .via(UnixDomainSocket().outgoingConnection(file))
      .runWith(Sink.head)
}
Full source at GitHub
Java
connections.runForeach(
    connection -> {
      System.out.println("New connection from: " + connection.remoteAddress());

      final Flow<ByteString, ByteString, NotUsed> echo =
          Flow.of(ByteString.class)
              .via(
                  Framing.delimiter(
                      ByteString.fromString("\n"), 256, FramingTruncation.DISALLOW))
              .map(ByteString::utf8String)
              .map(s -> s + "!!!\n")
              .map(ByteString::fromString);

      connection.handleWith(echo, materializer);
    },
    materializer);
Full source at GitHub
The source code for this page can be found here.