Search in sources :

Example 81 with DatagramPacket

use of io.netty.channel.socket.DatagramPacket in project reactor-netty by reactor.

the class UdpClientTest method smokeTest.

@Test
void smokeTest() throws Exception {
    LoopResources resources = LoopResources.create("test");
    CountDownLatch latch = new CountDownLatch(4);
    Connection server = UdpServer.create().port(0).runOn(resources).handle((in, out) -> in.receiveObject().map(o -> {
        if (o instanceof DatagramPacket) {
            DatagramPacket received = (DatagramPacket) o;
            ByteBuf buffer = received.content();
            System.out.println("Server received " + buffer.readCharSequence(buffer.readableBytes(), CharsetUtil.UTF_8));
            ByteBuf buf1 = Unpooled.copiedBuffer("echo ", CharsetUtil.UTF_8);
            ByteBuf buf2 = Unpooled.copiedBuffer(buf1, buffer);
            buf1.release();
            return new DatagramPacket(buf2, received.sender());
        } else {
            return Mono.error(new Exception());
        }
    }).flatMap(out::sendObject)).wiretap(true).bind().block(Duration.ofSeconds(30));
    assertThat(server).isNotNull();
    InetSocketAddress address = (InetSocketAddress) server.address();
    Connection client1 = UdpClient.create().port(address.getPort()).runOn(resources).handle((in, out) -> {
        in.receive().subscribe(b -> latch.countDown());
        return out.sendString(Mono.just("ping1")).then(out.sendString(Mono.just("ping2"))).neverComplete();
    }).wiretap(true).connect().block(Duration.ofSeconds(30));
    assertThat(client1).isNotNull();
    Connection client2 = UdpClient.create().port(address.getPort()).runOn(resources).handle((in, out) -> {
        in.receive().subscribe(b -> latch.countDown());
        return out.sendString(Mono.just("ping3")).then(out.sendString(Mono.just("ping4"))).neverComplete();
    }).wiretap(true).connect().block(Duration.ofSeconds(30));
    assertThat(client2).isNotNull();
    assertThat(latch.await(30, TimeUnit.SECONDS)).as("latch await").isTrue();
    server.disposeNow();
    client1.disposeNow();
    client2.disposeNow();
}
Also used : LoopResources(reactor.netty.resources.LoopResources) StepVerifier(reactor.test.StepVerifier) Assumptions.assumeThat(org.assertj.core.api.Assumptions.assumeThat) Files(java.nio.file.Files) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) DomainDatagramPacket(io.netty.channel.unix.DomainDatagramPacket) Mono(reactor.core.publisher.Mono) InetSocketAddress(java.net.InetSocketAddress) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Unpooled(io.netty.buffer.Unpooled) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuf(io.netty.buffer.ByteBuf) DomainSocketAddress(io.netty.channel.unix.DomainSocketAddress) Duration(java.time.Duration) DatagramPacket(io.netty.channel.socket.DatagramPacket) CharsetUtil(io.netty.util.CharsetUtil) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) Connection(reactor.netty.Connection) InetSocketAddress(java.net.InetSocketAddress) LoopResources(reactor.netty.resources.LoopResources) DomainDatagramPacket(io.netty.channel.unix.DomainDatagramPacket) DatagramPacket(io.netty.channel.socket.DatagramPacket) Connection(reactor.netty.Connection) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuf(io.netty.buffer.ByteBuf) FileNotFoundException(java.io.FileNotFoundException) Test(org.junit.jupiter.api.Test)

Example 82 with DatagramPacket

use of io.netty.channel.socket.DatagramPacket in project atomix by atomix.

the class NettyBroadcastService method bootstrapClient.

private CompletableFuture<Void> bootstrapClient() {
    Bootstrap clientBootstrap = new Bootstrap().group(group).channelFactory(() -> new NioDatagramChannel(InternetProtocolFamily.IPv4)).handler(new SimpleChannelInboundHandler<DatagramPacket>() {

        @Override
        protected void channelRead0(ChannelHandlerContext context, DatagramPacket packet) throws Exception {
            byte[] payload = new byte[packet.content().readInt()];
            packet.content().readBytes(payload);
            Message message = SERIALIZER.decode(payload);
            Set<Consumer<byte[]>> listeners = NettyBroadcastService.this.listeners.get(message.subject());
            if (listeners != null) {
                for (Consumer<byte[]> listener : listeners) {
                    listener.accept(message.payload());
                }
            }
        }
    }).option(ChannelOption.IP_MULTICAST_IF, iface).option(ChannelOption.SO_REUSEADDR, true).localAddress(localAddress.getPort());
    CompletableFuture<Void> future = new CompletableFuture<>();
    clientBootstrap.bind().addListener((ChannelFutureListener) f -> {
        if (f.isSuccess()) {
            clientChannel = (DatagramChannel) f.channel();
            log.info("{} joining multicast group {} on port {}", localAddress.getHostName(), groupAddress.getHostName(), groupAddress.getPort());
            clientChannel.joinGroup(groupAddress, iface).addListener(f2 -> {
                if (f2.isSuccess()) {
                    log.info("{} successfully joined multicast group {} on port {}", localAddress.getHostName(), groupAddress.getHostName(), groupAddress.getPort());
                    future.complete(null);
                } else {
                    log.info("{} failed to join group {} on port {}", localAddress.getHostName(), groupAddress.getHostName(), groupAddress.getPort());
                    future.completeExceptionally(f2.cause());
                }
            });
        } else {
            future.completeExceptionally(f.cause());
        }
    });
    return future;
}
Also used : SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) Address(io.atomix.utils.net.Address) ChannelOption(io.netty.channel.ChannelOption) AtomixRuntimeException(io.atomix.utils.AtomixRuntimeException) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) SocketException(java.net.SocketException) Threads.namedThreads(io.atomix.utils.concurrent.Threads.namedThreads) Namespaces(io.atomix.utils.serializer.Namespaces) DatagramChannel(io.netty.channel.socket.DatagramChannel) ByteBuf(io.netty.buffer.ByteBuf) ChannelFutureListener(io.netty.channel.ChannelFutureListener) Map(java.util.Map) DatagramPacket(io.netty.channel.socket.DatagramPacket) BroadcastService(io.atomix.cluster.messaging.BroadcastService) InternetProtocolFamily(io.netty.channel.socket.InternetProtocolFamily) ManagedBroadcastService(io.atomix.cluster.messaging.ManagedBroadcastService) EventLoopGroup(io.netty.channel.EventLoopGroup) Logger(org.slf4j.Logger) NetworkInterface(java.net.NetworkInterface) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) Set(java.util.Set) Maps(com.google.common.collect.Maps) InetSocketAddress(java.net.InetSocketAddress) Sets(com.google.common.collect.Sets) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Channel(io.netty.channel.Channel) Consumer(java.util.function.Consumer) Bootstrap(io.netty.bootstrap.Bootstrap) Namespace(io.atomix.utils.serializer.Namespace) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) Serializer(io.atomix.utils.serializer.Serializer) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) DatagramChannel(io.netty.channel.socket.DatagramChannel) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CompletableFuture(java.util.concurrent.CompletableFuture) Consumer(java.util.function.Consumer) DatagramPacket(io.netty.channel.socket.DatagramPacket) Bootstrap(io.netty.bootstrap.Bootstrap)

Example 83 with DatagramPacket

use of io.netty.channel.socket.DatagramPacket in project atomix by atomix.

the class NettyBroadcastService method broadcast.

@Override
public void broadcast(String subject, byte[] payload) {
    if (enabled) {
        Message message = new Message(subject, payload);
        byte[] bytes = SERIALIZER.encode(message);
        ByteBuf buf = serverChannel.alloc().buffer(4 + bytes.length);
        buf.writeInt(bytes.length).writeBytes(bytes);
        serverChannel.writeAndFlush(new DatagramPacket(buf, groupAddress));
    }
}
Also used : DatagramPacket(io.netty.channel.socket.DatagramPacket) ByteBuf(io.netty.buffer.ByteBuf)

Example 84 with DatagramPacket

use of io.netty.channel.socket.DatagramPacket in project atomix by atomix.

the class NettyUnicastService method bootstrap.

private CompletableFuture<Void> bootstrap() {
    Bootstrap serverBootstrap = new Bootstrap().group(group).channel(NioDatagramChannel.class).handler(new SimpleChannelInboundHandler<DatagramPacket>() {

        @Override
        protected void channelRead0(ChannelHandlerContext context, DatagramPacket packet) throws Exception {
            byte[] payload = new byte[packet.content().readInt()];
            packet.content().readBytes(payload);
            Message message = SERIALIZER.decode(payload);
            Map<BiConsumer<Address, byte[]>, Executor> listeners = NettyUnicastService.this.listeners.get(message.subject());
            if (listeners != null) {
                listeners.forEach((consumer, executor) -> executor.execute(() -> consumer.accept(message.source(), message.payload())));
            }
        }
    }).option(ChannelOption.RCVBUF_ALLOCATOR, new DefaultMaxBytesRecvByteBufAllocator()).option(ChannelOption.SO_BROADCAST, true).option(ChannelOption.SO_REUSEADDR, true);
    return bind(serverBootstrap);
}
Also used : SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) Executor(java.util.concurrent.Executor) DatagramPacket(io.netty.channel.socket.DatagramPacket) Bootstrap(io.netty.bootstrap.Bootstrap) DefaultMaxBytesRecvByteBufAllocator(io.netty.channel.DefaultMaxBytesRecvByteBufAllocator) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) BiConsumer(java.util.function.BiConsumer)

Example 85 with DatagramPacket

use of io.netty.channel.socket.DatagramPacket in project atomix by atomix.

the class NettyUnicastService method unicast.

@Override
public void unicast(Address address, String subject, byte[] payload) {
    final InetAddress resolvedAddress = address.address();
    if (resolvedAddress == null) {
        LOGGER.debug("Failed sending unicast message (destination address {} cannot be resolved)", address);
        return;
    }
    Message message = new Message(this.address, subject, payload);
    byte[] bytes = SERIALIZER.encode(message);
    ByteBuf buf = channel.alloc().buffer(4 + bytes.length);
    buf.writeInt(bytes.length).writeBytes(bytes);
    channel.writeAndFlush(new DatagramPacket(buf, new InetSocketAddress(resolvedAddress, address.port())));
}
Also used : InetSocketAddress(java.net.InetSocketAddress) DatagramPacket(io.netty.channel.socket.DatagramPacket) ByteBuf(io.netty.buffer.ByteBuf) InetAddress(java.net.InetAddress)

Aggregations

DatagramPacket (io.netty.channel.socket.DatagramPacket)85 InetSocketAddress (java.net.InetSocketAddress)48 ByteBuf (io.netty.buffer.ByteBuf)45 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)16 Test (org.junit.Test)15 Channel (io.netty.channel.Channel)9 DatagramChannel (io.netty.channel.socket.DatagramChannel)9 Test (org.junit.jupiter.api.Test)9 ChannelFuture (io.netty.channel.ChannelFuture)8 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)8 CountDownLatch (java.util.concurrent.CountDownLatch)8 Bootstrap (io.netty.bootstrap.Bootstrap)7 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)7 NioDatagramChannel (io.netty.channel.socket.nio.NioDatagramChannel)6 InetAddress (java.net.InetAddress)6 ByteBuffer (java.nio.ByteBuffer)6 DefaultAddressedEnvelope (io.netty.channel.DefaultAddressedEnvelope)5 SimpleChannelInboundHandler (io.netty.channel.SimpleChannelInboundHandler)5 SocketAddress (java.net.SocketAddress)5 SocketException (java.net.SocketException)5