Java Nettty

UDP client example



public class UdpClient {
    public static void main(String[] args) {
        //服务类
        Bootstrap bootstrap = new Bootstrap();

        //worker
        EventLoopGroup worker = new NioEventLoopGroup();

        try {
            //设置线程池
            bootstrap.group(worker)
                    .channel(NioDatagramChannel.class)
                    .handler(new ChannelInitializer() {
                        @Override
                        protected void initChannel(Channel ch) throws Exception {
                            ch.pipeline().addLast(new ClientHandler());
                        }
                    });
            Channel connect = bootstrap.bind(0).sync().channel();

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                System.out.println("请输入:");
                String msg = bufferedReader.readLine();
                DatagramPacket datagramPacket = new DatagramPacket(Unpooled.wrappedBuffer(msg.getBytes()), new InetSocketAddress("127.0.0.1", 6001));
                connect.writeAndFlush(datagramPacket);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            worker.shutdownGracefully();
        }
    }
}

 

你可能感兴趣的:(Java Nettty)