Netty4框架的初步使用

Netty4框架的初步使用

Netty4的基本概念网上有很多,这里就不多说,这仅仅只是一个小例子。

功能模块分三部分:
1、Handler,消息处理
2、Client,客户端
3、Server,服务端

结构目录:
这里写图片描述

代码如下:

  • 公用的Handler
package com.zmm.netty4introduction.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public abstract class CommonHandler extends SimpleChannelInboundHandler<String> {


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {
        System.out.println("---" + ctx.channel().remoteAddress() + " 收到消息 = "+s);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("---" + ctx.channel().remoteAddress() + " 活跃中...");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("---" + ctx.channel().remoteAddress() + " 闲置中...");
    }

}
  • Client端

ClientHandler类:目前未做其他功能,继承公共Handler即可

package com.zmm.netty4introduction.client;

import com.zmm.netty4introduction.handler.CommonHandler;

public class ClientHandler extends CommonHandler {
}

Client类:

package com.zmm.netty4introduction.client;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class Client {

    private static final String host = "127.0.0.1";
    private static final int port = 7878;

    public static void main(String[] args) {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {

                            ChannelPipeline p = socketChannel.pipeline();

                            //String的编码器和解码器,netty提供,要和Server一致
                            p.addLast(new StringDecoder());
                            p.addLast(new StringEncoder());

                            p.addLast(new ClientHandler());
                        }
                    });

            // 连接服务端
            Channel ch = bootstrap.connect(host, port).sync().channel();

            System.out.println("---Server connect Success---");

            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            for (;;) {
                System.out.println("请输入:");
                String line = in.readLine();
                if (line == null) {
                    continue;
                }

                ch.writeAndFlush(line + "\r\n");
            }
        }catch (Exception e){
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }
}
  • 服务端
    ServerHandler类:这里做了一个处理,当收到客户端数据后,返回一条消息
package com.zmm.netty4introduction.server;

import com.zmm.netty4introduction.handler.CommonHandler;

import io.netty.channel.ChannelHandlerContext;

public class ServerHandler extends CommonHandler {

    private int count = 1;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {
        System.out.println("---Server 收到客户端消息 = "+s);

        ctx.writeAndFlush("服务端返回信息"+count++);

    }
}

Server类:

package com.zmm.netty4introduction.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class Server {

    private static final int port = 7878;

    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {

            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                     .channel(NioServerSocketChannel.class)
                     .childHandler(new ChannelInitializer<SocketChannel>() {
                         @Override
                         protected void initChannel(SocketChannel socketChannel) throws Exception {

                             ChannelPipeline p = socketChannel.pipeline();

                             //String的编码器和解码器,netty提供,要和Client一致
                             p.addLast(new StringDecoder());
                             p.addLast(new StringEncoder());

                             p.addLast(new ServerHandler());
                         }

            });

            // 服务器绑定端口监听
            Channel ch = bootstrap.bind(port).sync().channel();

            System.out.println("---Server Start---");

            ch.closeFuture().sync();

        } catch (Exception e){
            throw new RuntimeException(e);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

注意事项:

1、因为未做特殊处理,所以要先运行Server,再运行Client。
2、若要先运行Client也可以,可以看下一篇,接着会写一篇Netty4长连接的文章,里面会用Msgpack传递数据,其中会包括Tcp长连接、断开重连、心跳监测、Msgpack的编码和解码等。

GitHub:Netty4Introduction
(直接在AndroidStudio上运行即可)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值