java 网络通信 netty UDP Hello World(基于Netty5.0)

  • 服务器端
public class SearchServer {
    public static void initServer() {//udp服务端,接受客户端发送的广播
        try {
            Bootstrap b = new Bootstrap();
            EventLoopGroup group = new NioEventLoopGroup();
            b.group(group)
                    .channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new UdpServerHandler());
            b.bind(AppConstants.SEARCH_PORT).sync().channel().closeFuture().await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static class UdpServerHandler extends SimpleChannelInboundHandler {
        @Override
        protected void messageReceived(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
            ByteBuf buf = packet.copy().content();
            byte[] req = new byte[buf.readableBytes()];
            buf.readBytes(req);
            String body = new String(req, "UTF-8");
            Log.d("TAG", body);
            System.out.println(body);//打印收到的信息

            //向客户端发送消息
            String json = "给客户端发送的内容";

            // 由于数据报的数据是以字符数组传的形式存储的,所以传转数据
            byte[] bytes = json.getBytes("UTF-8");
            DatagramPacket data = new DatagramPacket(Unpooled.copiedBuffer(bytes), packet.sender());
            ctx.writeAndFlush(data);//向客户端发送消息
        }
    }

}
  • 客户端
public class SearchClient {

    public static final int MessageReceived = 0x99;
    private int scanPort;

    public SearchClient(int scanPort) {
            this.scanPort = scanPort;
    }


    private static class CLientHandler extends SimpleChannelInboundHandler {
        @Override
        protected void messageReceived(ChannelHandlerContext ctx,
                                       DatagramPacket packet) throws Exception {

         String  body =  packet.content().toString(CharsetUtil.UTF_8);
            Log.i("Search", "body:" + body);
            //这里接收到服务端发送的内容

        }
    }

    public void sendPackage() {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new CLientHandler());

            Channel ch = b.bind(0).sync().channel();

            ch.writeAndFlush(new DatagramPacket(
                    Unpooled.copiedBuffer("Searh:", CharsetUtil.UTF_8),
                    new InetSocketAddress("255.255.255.255", scanPort))).sync();

            Log.i("Searh","sendPackage()");

            // QuoteOfTheMomentClientHandler will close the DatagramChannel when a
            // response is received.  If the channel is not closed within 5 seconds,
            // print an error message and quit.
            if (!ch.closeFuture().await(5000)) {
                System.err.println("Search request timed out.");
            }
        }catch (Exception e){
            e.printStackTrace();
            Log.e("Search","An Error Occur",e);
        }
        finally {
            group.shutdownGracefully();
        }
    }
}

你可能感兴趣的:(java 网络通信 netty UDP Hello World(基于Netty5.0))