!act #15626 expose DatagramChannel creation in DatagramChannelCreator

* move channel creation logic to a separate trait
* new Java API: AbstractSocketOption
This commit is contained in:
Martynas Mickevicius 2014-08-19 14:02:23 +03:00
parent eb766d49f3
commit 325e05ee27
12 changed files with 466 additions and 6 deletions

View file

@ -0,0 +1,59 @@
/**
* Copyright (C) 2009-2014 Typesafe Inc. <http://www.typesafe.com>
*/
package docs.io
import java.net.{InetAddress, InetSocketAddress, NetworkInterface, StandardProtocolFamily}
import java.nio.channels.DatagramChannel
import akka.actor.{Actor, ActorLogging, ActorRef}
import akka.io.Inet.{DatagramChannelCreator, SocketOption}
import akka.io.{IO, Udp}
import akka.util.ByteString
//#inet6-protocol-family
final case class Inet6ProtocolFamily() extends DatagramChannelCreator {
override def create() =
DatagramChannel.open(StandardProtocolFamily.INET6)
}
//#inet6-protocol-family
//#multicast-group
final case class MulticastGroup(address: String, interface: String) extends SocketOption {
override def afterConnect(c: DatagramChannel) {
val group = InetAddress.getByName(address)
val networkInterface = NetworkInterface.getByName(interface)
c.join(group, networkInterface)
}
}
//#multicast-group
class Listener(iface: String, group: String, port: Int, sink: ActorRef) extends Actor with ActorLogging {
//#bind
import context.system
val opts = List(Inet6ProtocolFamily(), MulticastGroup(group, iface))
IO(Udp) ! Udp.Bind(self, new InetSocketAddress(port), opts)
//#bind
def receive = {
case Udp.Bound(to) => log.info(s"Bound to $to")
case Udp.Received(data, remote) =>
val msg = data.decodeString("utf-8")
log.info(s"Received '$msg' from '$remote'")
sink ! msg
}
}
class Sender(group: String, port: Int, msg: String) extends Actor with ActorLogging {
import context.system
IO(Udp) ! Udp.SimpleSender(List(Inet6ProtocolFamily()))
def receive = {
case Udp.SimpleSenderReady => {
val remote = new InetSocketAddress(group, port)
log.info(s"Sending message to $remote")
sender() ! Udp.Send(ByteString(msg), remote)
}
}
}