Last active
May 20, 2019 05:23
-
-
Save crised/73fe3e87220fef4611f6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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