use of io.netty.channel.socket.DatagramPacket in project alliance by codice.
the class MpegTsUdpClient method transmit.
private static void transmit(Channel ch, byte[] buf, String ip, int port) throws InterruptedException {
ChannelFuture cf = ch.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(buf), new InetSocketAddress(ip, port)));
cf.await();
}
use of io.netty.channel.socket.DatagramPacket in project alliance by codice.
the class MpegTsUdpClient method broadcastVideo.
public static void broadcastVideo(String videoFilePath, String ip, int port, long tsDurationMillis, int minDatagramSize, int maxDatagramSize, boolean fractionalTs, String networkInterfaceName) {
Optional<InetAddress> inetAddressOptional = findLocalAddress(networkInterfaceName);
EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(eventLoopGroup).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true).handler(new SimpleChannelInboundHandler<DatagramPacket>() {
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, DatagramPacket datagramPacket) throws Exception {
LOGGER.trace("Reading datagram from channel");
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
LOGGER.error("Exception occurred while handling datagram packet.", cause);
ctx.close();
}
});
Channel ch;
if (inetAddressOptional.isPresent()) {
ch = bootstrap.bind(inetAddressOptional.get(), 0).sync().channel();
} else {
ch = bootstrap.bind(0).sync().channel();
}
File videoFile = new File(videoFilePath);
long bytesSent = 0;
long tsPacketCount = videoFile.length() / PACKET_SIZE;
double delayPerPacket = tsDurationMillis / (double) tsPacketCount;
long startTime = System.currentTimeMillis();
Random rand = new Random(0);
long nextPacketLog = PACKET_LOG_PERIOD;
long nextByteLog = BYTE_LOG_PERIOD;
try (final InputStream fis = new BufferedInputStream(new FileInputStream(videoFile))) {
byte[] buffer = new byte[DISK_IO_BUFFER_SIZE];
int datagramSize = getPacketSize(rand, minDatagramSize, maxDatagramSize, fractionalTs);
byte[] dgramBuffer = new byte[datagramSize];
int writeStart = 0;
int writeEnd = datagramSize;
int readEnd;
while ((readEnd = fis.read(buffer)) != -1) {
int readStart = 0;
while (readStart < readEnd) {
int bytesToCopy = Math.min(writeEnd - writeStart, readEnd - readStart);
System.arraycopy(buffer, readStart, dgramBuffer, writeStart, bytesToCopy);
readStart += bytesToCopy;
writeStart += bytesToCopy;
if (writeStart == writeEnd) {
transmit(ch, dgramBuffer, ip, port);
bytesSent += dgramBuffer.length;
long packetsSent = bytesSent / PACKET_SIZE;
long currentTime = System.currentTimeMillis();
long elapsedTime = currentTime - startTime;
double predictedTime = packetsSent * delayPerPacket;
if ((predictedTime - elapsedTime) >= 50) {
Thread.sleep((long) predictedTime - elapsedTime);
}
if (packetsSent >= nextPacketLog) {
LOGGER.debug("Packets sent: {}, Bytes sent: {}", packetsSent, bytesSent);
nextPacketLog += PACKET_LOG_PERIOD;
}
if (bytesSent >= nextByteLog) {
LOGGER.debug("Packets sent: {}, Bytes sent: {}", packetsSent, bytesSent);
nextByteLog += BYTE_LOG_PERIOD;
}
datagramSize = getPacketSize(rand, minDatagramSize, maxDatagramSize, fractionalTs);
dgramBuffer = new byte[datagramSize];
writeStart = 0;
writeEnd = datagramSize;
}
}
}
if (writeStart > 0) {
byte[] tmp = new byte[writeStart];
System.arraycopy(dgramBuffer, 0, tmp, 0, tmp.length);
transmit(ch, tmp, ip, port);
}
}
long endTime = System.currentTimeMillis();
LOGGER.trace("Time Elapsed: {}", endTime - startTime);
LOGGER.trace("Elapsed Time minus predicted time: {}", (endTime - startTime) - tsDurationMillis);
if (!ch.closeFuture().await(100)) {
LOGGER.error("Channel timeout");
}
LOGGER.trace("Bytes sent: {} ", bytesSent);
} catch (InterruptedException | IOException e) {
LOGGER.error("Unable to generate stream.", e);
} finally {
// Shut down the event loop to terminate all threads.
eventLoopGroup.shutdownGracefully();
}
}
use of io.netty.channel.socket.DatagramPacket in project reactor-netty by reactor.
the class UdpClientTest method smokeTest.
@Test
public void smokeTest() throws Exception {
LoopResources resources = LoopResources.create("test");
CountDownLatch latch = new CountDownLatch(4);
NettyContext server = UdpServer.create(ops -> ops.port(0).loopResources(resources)).newHandler((in, out) -> in.receiveObject().map(o -> {
if (o instanceof DatagramPacket) {
DatagramPacket received = (DatagramPacket) o;
System.out.println("Server received " + received.content().toString(CharsetUtil.UTF_8));
ByteBuf buf1 = Unpooled.copiedBuffer("echo ", CharsetUtil.UTF_8);
ByteBuf buf2 = Unpooled.copiedBuffer(buf1, received.content().retain());
return new DatagramPacket(buf2, received.sender());
} else {
return Mono.error(new Exception());
}
}).flatMap(p -> out.sendObject(p))).block(Duration.ofSeconds(30));
NettyContext client1 = UdpClient.create(ops -> ops.port(server.address().getPort()).loopResources(resources)).newHandler((in, out) -> {
in.receive().subscribe(b -> {
System.out.println("Client1 received " + b.toString(CharsetUtil.UTF_8));
latch.countDown();
});
return out.sendString(Mono.just("ping1")).then(out.sendString(Mono.just("ping2"))).neverComplete();
}).block(Duration.ofSeconds(30));
NettyContext client2 = UdpClient.create(ops -> ops.port(server.address().getPort()).loopResources(resources)).newHandler((in, out) -> {
in.receive().subscribe(b -> {
System.out.println("Client2 received " + b.toString(CharsetUtil.UTF_8));
latch.countDown();
});
return out.sendString(Mono.just("ping3")).then(out.sendString(Mono.just("ping4"))).neverComplete();
}).block(Duration.ofSeconds(30));
assertTrue(latch.await(30, TimeUnit.SECONDS));
server.dispose();
client1.dispose();
client2.dispose();
}
use of io.netty.channel.socket.DatagramPacket in project ribbon by Netflix.
the class UdpClientTest method testUdpClientWithoutTimeout.
@Test
public void testUdpClientWithoutTimeout() throws Exception {
int port = choosePort();
UdpServer<DatagramPacket, DatagramPacket> server = new HelloUdpServer(port, 0).createServer();
server.start();
BaseLoadBalancer lb = new BaseLoadBalancer();
lb.setServersList(Lists.newArrayList(new Server("localhost", port)));
RxClient<DatagramPacket, DatagramPacket> client = RibbonTransport.newUdpClient(lb, DefaultClientConfigImpl.getClientConfigWithDefaultValues());
try {
String response = client.connect().flatMap(new Func1<ObservableConnection<DatagramPacket, DatagramPacket>, Observable<DatagramPacket>>() {
@Override
public Observable<DatagramPacket> call(ObservableConnection<DatagramPacket, DatagramPacket> connection) {
connection.writeStringAndFlush("Is there anybody out there?");
return connection.getInput();
}
}).take(1).map(new Func1<DatagramPacket, String>() {
@Override
public String call(DatagramPacket datagramPacket) {
return datagramPacket.content().toString(Charset.defaultCharset());
}
}).toBlocking().first();
assertEquals(HelloUdpServer.WELCOME_MSG, response);
} finally {
server.shutdown();
}
}
use of io.netty.channel.socket.DatagramPacket in project vert.x by eclipse.
the class DatagramSocketImpl method send.
@Override
public Future<Void> send(Buffer packet, int port, String host) {
Objects.requireNonNull(packet, "no null packet accepted");
Objects.requireNonNull(host, "no null host accepted");
if (port < 0 || port > 65535) {
throw new IllegalArgumentException("port out of range:" + port);
}
AddressResolver resolver = context.owner().addressResolver();
PromiseInternal<Void> promise = context.promise();
io.netty.util.concurrent.Future<InetSocketAddress> f1 = resolver.resolveHostname(context.nettyEventLoop(), host);
f1.addListener((GenericFutureListener<io.netty.util.concurrent.Future<InetSocketAddress>>) res1 -> {
if (res1.isSuccess()) {
ChannelFuture f2 = channel.writeAndFlush(new DatagramPacket(packet.getByteBuf(), new InetSocketAddress(f1.getNow().getAddress(), port)));
if (metrics != null) {
f2.addListener(fut -> {
if (fut.isSuccess()) {
metrics.bytesWritten(null, SocketAddress.inetSocketAddress(port, host), packet.length());
}
});
}
f2.addListener(promise);
} else {
promise.fail(res1.cause());
}
});
return promise.future();
}
Aggregations