UDP

The UDP connector provides Akka Stream flows that allow to send and receive UDP datagrams.

Reported issues

Tagged issues at Github

Artifacts

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

Usage

Sending

Datagrams can be sent to remote destinations by using a Udp.sendFlow or Udp.sendSink which can be found in the Udp factory object.

Scala
val destination = new InetSocketAddress("my.server", 27015)
val messagesToSend = 100

Source(1 to messagesToSend)
  .map(i => ByteString(s"Message $i"))
  .map(Datagram(_, destination))
  .runWith(Udp.sendSink())
Full source at GitHub
Java
final InetSocketAddress destination = new InetSocketAddress("my.server", 27015);
final Integer messagesToSend = 100;

Source.range(1, messagesToSend)
    .map(i -> ByteString.fromString("Message " + i))
    .map(bs -> Datagram.create(bs, destination))
    .runWith(Udp.sendSink(system), materializer);
Full source at GitHub

Receiving

First create an address which will be used to bind and listen for incoming datagrams.

Scala
val bindToLocal = new InetSocketAddress("localhost", 0)
Full source at GitHub
Java
final InetSocketAddress bindToLocal = new InetSocketAddress("localhost", 0);
Full source at GitHub

A Flow created from Udp.bindFlow will bind to the given address. All datagrams coming from the network to the bound address will be sent downstream. Datagrams received from the upstream will be sent to their corresponding destination addresses.

The flow materializes to the Future[InetSocketAddress]CompletionStage<InetSocketAddress> which will eventually hold the address the flow was finally bound to.

Scala
val bindFlow: Flow[Datagram, Datagram, Future[InetSocketAddress]] =
  Udp.bindFlow(bindToLocal)
Full source at GitHub
Java
final Flow<Datagram, Datagram, CompletionStage<InetSocketAddress>> bindFlow =
  Udp.bindFlow(bindToLocal, system);
Full source at GitHub

Running the example code

The code in this guide is part of runnable tests of this project. You are welcome to browse the code, edit and run it in sbt.

Scala
sbt
> udp/testOnly *.UdpSpec
Java
sbt
> udp/testOnly *.UdpTest
The source code for this page can be found here.