Skip to content

Instantly share code, notes, and snippets.

@crised
Last active May 20, 2019 05:23
Show Gist options
  • Save crised/73fe3e87220fef4611f6 to your computer and use it in GitHub Desktop.
Save crised/73fe3e87220fef4611f6 to your computer and use it in GitHub Desktop.
@Test
public void sendUdp() {
Netty netty = new Netty();
Channel channel = netty.bootstrap();
try {
ChannelFuture channelFuture = channel.writeAndFlush(new Object());
channelFuture.addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture future) {
LOG.info("done!!");
}
});
channelFuture.await(2, TimeUnit.SECONDS);
} catch (Exception e) {
LOG.info("exception", e);
}
channel.close();
netty.shutdown();
}
-------
public class Netty {
static final Logger LOG = LoggerFactory.getLogger(CL_TELEMATIC);
EventLoopGroup group = new NioEventLoopGroup();
public Channel bootstrap() {
try {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioDatagramChannel.class)
.handler(new ChannelInitializer<NioDatagramChannel>() {
@Override
protected void initChannel(NioDatagramChannel nioDatagramChannel) throws Exception {
nioDatagramChannel.pipeline().addLast(new Handler());
}
});
return b.bind("192.168.1.11", 20800).sync().channel();
} catch (InterruptedException e) {
LOG.error("netty exception", e);
return null;
}
}
public void shutdown(){
group.shutdownGracefully();
}
}
----
public class Handler extends ChannelOutboundHandlerAdapter {
static final Logger LOG = LoggerFactory.getLogger(CL_TELEMATIC);
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
try {
LOG.info("in write method");
ByteBuf buf = ctx.alloc().buffer();
buf.writeByte(0x00);
LOG.info("bytebuf allocating");
DatagramPacket datagramPacket = new DatagramPacket(buf, new InetSocketAddress("200.72.211.71", 20800));
LOG.info(datagramPacket.toString());
ctx.writeAndFlush(datagramPacket);
LOG.info("writing");
} catch (Exception e) {
LOG.info("exception", e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment