博客
关于我
netty服务器,客户端初体验
阅读量:174 次
发布时间:2019-02-28

本文共 4130 字,大约阅读时间需要 13 分钟。

一、引入依赖

在项目中首先需要配置所需的依赖包。Netty作为依赖包需要手动添加,建议访问Maven仓库获取最新版本。以下是常用的依赖配置:

io.netty
netty-all
4.1.25.Final
org.projectlombok
lombok
1.16.22

二、服务器端实现

完成依赖配置后,接下来编写服务器端代码。以下是一个简单的Netty服务器实现:

public class LiuServer {    private final int port;    public LiuServer(int port) {        this.port = port;    }    public static void main(String[] args) throws Exception {        int port = 8888;        new LiuServer(port).start();    }    public void start() throws Exception {        EventLoopGroup bossGroup = new NioEventLoopGroup(1);        EventLoopGroup workerGroup = new NioEventLoopGroup();        try {            ServerBootstrap b = new ServerBootstrap();            b.group(bossGroup, workerGroup)                    .channel(NioServerSocketChannel.class)                    .localAddress(new InetSocketAddress(port))                    .childHandler(new ChannelInitializer
() { @Override public void initChannel(SocketChannel ch) { ch.pipeline().addLast(new LiuServerHandler()); } }); ChannelFuture f = b.bind().sync(); System.out.println(LiuServer.class.getName() + " 服务启动开始监听端口:" + f.channel().localAddress()); f.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }}//服务器处理类@ChannelHandler.Sharablepublic class LiuServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { ByteBuf in = (ByteBuf) msg; System.out.println("客户端发来消息: " + in.toString(CharsetUtil.UTF_8)); ctx.write(in); } @Override public void channelReadComplete(ChannelHandlerContext ctx) { System.out.println("channel 通道读取完成"); ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); }}

三、客户端实现

客户端需要连接到服务器,以下是一个简单的Netty客户端实现:

public class LiuClient {    private final String host;    private final int port;    public LiuClient(String host, int port) {        this.host = host;        this.port = port;    }    public static void main(String[] args) throws Exception {        final String host = "127.0.0.1";        final int port = 8888;        new LiuClient(host, port).start();    }    public void start() throws Exception {        EventLoopGroup group = new NioEventLoopGroup();        try {            Bootstrap b = new Bootstrap();            b.group(group)                    .channel(NioSocketChannel.class)                    .remoteAddress(new InetSocketAddress(host, port))                    .handler(new ChannelInitializer
() { @Override public void initChannel(SocketChannel ch) { ch.pipeline().addLast(new LiuClientHandler()); } }); ChannelFuture f = b.connect().sync(); f.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } }}//客户端处理类@ChannelHandler.Sharablepublic class LiuClientHandler extends SimpleChannelInboundHandler
{ @Override public void channelActive(ChannelHandlerContext ctx) { ctx.writeAndFlush(Unpooled.copiedBuffer("Hello Netty! " + Long.toString(System.currentTimeMillis()), CharsetUtil.UTF_8)); } @Override public void channelRead0(ChannelHandlerContext ctx, ByteBuf in) { System.out.println("服务器发来消息: " + in.toString(CharsetUtil.UTF_8)); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); }}

以上代码提供了一个完整的Netty服务器端和客户端实现,适用于基础的网络通信应用开发。

转载地址:http://mton.baihongyu.com/

你可能感兴趣的文章
Objective-C实现Bilateral Filter双边滤波器算法(附完整源码)
查看>>
Objective-C实现binary exponentiation二进制幂运算算法(附完整源码)
查看>>
Objective-C实现binary search二分查找算法(附完整源码)
查看>>
Objective-C实现binary tree mirror二叉树镜像算法(附完整源码)
查看>>
Objective-C实现binary tree traversal二叉树遍历算法(附完整源码)
查看>>
Objective-C实现BinarySearchTreeNode树算法(附完整源码)
查看>>
Objective-C实现binarySearch二分查找算法(附完整源码)
查看>>
Objective-C实现binomial coefficient二项式系数算法(附完整源码)
查看>>
Objective-C实现binomial distribution二项分布算法(附完整源码)
查看>>
Objective-C实现bisection二分法算法(附完整源码)
查看>>
Objective-C实现bisection二等分算法(附完整源码)
查看>>
Objective-C实现BitMap算法(附完整源码)
查看>>
Objective-C实现bitmask位掩码算法(附完整源码)
查看>>
Objective-C实现bitonic sort双调排序算法(附完整源码)
查看>>
Objective-C实现BloomFilter布隆过滤器的算法(附完整源码)
查看>>
Objective-C实现BMP图像旋转180度(附完整源码)
查看>>
Objective-C实现bogo sort排序算法(附完整源码)
查看>>
Objective-C实现boruvka博鲁夫卡算法(附完整源码)
查看>>
Objective-C实现Boyer-Moore字符串搜索算法(附完整源码)
查看>>
Objective-C实现BP误差逆传播算法(附完整源码)
查看>>