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();
}
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;
}
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));
}
}
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);
}
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())));
}
Aggregations