Netty实现UDP服务

目录

服务端

package com.cnblogs.javalouvre;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static io.netty.buffer.Unpooled.copiedBuffer;
import static java.nio.charset.StandardCharsets.UTF_8;

public class Server {

    private static final Logger log = LoggerFactory.getLogger(Server.class);
    private static final int   PORT = 5678;

    public static void main(String[] args) {
        new Server().bind();
    }

    private void bind() {
        final Bootstrap bootstrap = new Bootstrap();
        final EventLoopGroup group = new NioEventLoopGroup();
        bootstrap.group(group)
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, Boolean.TRUE)
                .handler(new ChannelInitializer<NioDatagramChannel>() {

                    @Override
                    protected void initChannel(NioDatagramChannel ch) throws Exception {
                        final ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new LoggingHandler());
                        pipeline.addLast(new SimpleChannelInboundHandler<DatagramPacket>() {

                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket dp) throws Exception {
                                log.info("服务器收到消息:{}", dp.content().toString(UTF_8));

                                ctx.writeAndFlush(new DatagramPacket(copiedBuffer("COPY THAT.".getBytes(UTF_8)), dp.sender()));
                            }

                        });
                    }

                });
        try {
            bootstrap.bind(PORT).sync().channel().closeFuture().await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }

}
posted @ 2022-05-06 15:10  Bruce.Chang.Lee  阅读(5)  评论(0编辑  收藏  举报