Netty android移动端通讯简单封装

由于公司最近做即时通讯,该文章是基于netty-all-4.1.25.Final.jar 版本5 在android中有问题 运行时候加载不到相关类 很是纳闷哪位同学 有解决方案 可以交流下。minaDemo可看另一片文章。
代码地址:https://github.com/mygzk/NettyAndroidDemo.git
先看效果图:

device-2018-06-22-170316.png

客户端 基于android移动的:

/**
 * netty client
 */
public class NettyClient {
    private String TAG = NettyClient.class.getSimpleName();
    /**
     * 重连间隔时间
     */
    private long reconnectIntervalTime = 5000;
    /**
     * 连接状态
     */
    private volatile boolean isConnect = false;
    /**
     * 是否需要重连
     */
    private boolean isNeedReconnect = true;
    /**
     * 重连次数
     */
    private static int reconnectNum = Integer.MAX_VALUE;

    private EventLoopGroup mEventLoopGroup;
    private Channel mChannel;
    private NettyClientHandler mNettyClientHandler;
    private DispterMessage mDispterMessage;
    private Thread mClientThread;

    private NettyConnectListener mNettyConnectListener;
    private List<NettyReceiveListener> mNettyReceiveListeners = new ArrayList<>();
    private NettyReceiveListener mNettyReceiveListener;


    private static class NettyClientHint {
        private static final NettyClient INSTANCE = new NettyClient();
    }

    private NettyClient() {
        mNettyClientHandler = new NettyClientHandler();
        mDispterMessage = new DispterMessage();
    }

    public static NettyClient getInstance() {
        return NettyClientHint.INSTANCE;
    }

    public void connect(NettyConnectListener listener) {
        if (isConnect) {
            return;
        }
        mNettyReceiveListeners.clear();

        mNettyConnectListener = listener;
        mClientThread = new Thread(new Runnable() {
            @Override
            public void run() {
                connectServer();
            }
        });
        mClientThread.start();
    }

    /**
     * 连接到netty服务器
     */
    private void connectServer() {
        if (mChannel != null) {
            mChannel = null;
        }
        try {
            mEventLoopGroup = new NioEventLoopGroup();
            Bootstrap mBootstrap = new Bootstrap();
            mBootstrap.group(mEventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            //粘包处理
                            pipeline.addLast("line", new LineBasedFrameDecoder(1024));
                            pipeline.addLast("decoder", new StringDecoder());
                            pipeline.addLast("encoder", new StringEncoder());
                            pipeline.addLast("handler", mNettyClientHandler);
                        }
                    });

            ChannelFuture mChannelFuture = mBootstrap
                    .connect(new InetSocketAddress(NettyConstant.HOST, NettyConstant.PORT)).sync();
            mChannel = mChannelFuture.channel();
            mChannelFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if (channelFuture.isSuccess()) {
                        isConnect = true;
                        mChannel = channelFuture.channel();
                        if (mNettyConnectListener != null) {
                            //   mNettyConnectListener.connectSucc();
                            postMsg(null, mNettyConnectListener, null, DispterMessage.MSG_CONN_SUCC);
                        }

                    } else {
                        if (mNettyConnectListener != null) {
                            //   mNettyConnectListener.connectFail("连接失败,channelFuture is not success");
                            postMsg("连接失败,channelFuture is not success", mNettyConnectListener, null, DispterMessage.MSG_CONN_FAIL);
                        }
                        isConnect = false;

                    }

                }
            });
            mChannel.closeFuture().sync();
        } catch (InterruptedException e) {
            if (mNettyConnectListener != null) {
                //  mNettyConnectListener.connectFail(e.getMessage());
                postMsg(e.getMessage(), mNettyConnectListener, null, DispterMessage.MSG_CONN_FAIL);
            }
            isConnect = false;
            e.printStackTrace();
        } catch (Exception e) {
            if (mNettyConnectListener != null) {
                postMsg(e.getMessage(), mNettyConnectListener, null, DispterMessage.MSG_CONN_FAIL);
            }
            e.printStackTrace();
        } finally {
            isConnect = false;
            if (mNettyConnectListener != null) {
                postMsg(null, mNettyConnectListener, null, DispterMessage.MSG_CONN_DIS);
            }
            disconnect();
            mEventLoopGroup.shutdownGracefully();

        }


    }

    public void disconnect() {
       /* if (mClientThread != null) {
            mClientThread.interrupt();
            mClientThread = null;
        }*/
        if (mNettyConnectListener != null) {
            postMsg(null, mNettyConnectListener, null, DispterMessage.MSG_CONN_DIS);
        }
        clearReceiveLisenter();

        isConnect = false;
        isNeedReconnect = false;
        mEventLoopGroup.shutdownGracefully();
    }

    public void reconnect() {
        Log.e(TAG, "reconnect");
        if (isNeedReconnect && reconnectNum > 0 && !isConnect) {
            reconnectNum--;
            SystemClock.sleep(reconnectIntervalTime);
            if (isNeedReconnect && reconnectNum > 0 && !isConnect) {
                disconnect();
                SystemClock.sleep(reconnectIntervalTime);
                connectServer();
            }
        }
    }

    public synchronized void send(String msg, NettyReceiveListener listener) {
        mNettyReceiveListener = listener;
        if (mChannel == null) {
            postMsg("channel is null", null, mNettyReceiveListener, DispterMessage.MSG_RECEIVE_FAIL);
            return;
        }

        if (!mChannel.isWritable()) {
            postMsg("channel is not Writable", null, mNettyReceiveListener, DispterMessage.MSG_RECEIVE_FAIL);
            return;
        }
        if (!mChannel.isActive()) {
            postMsg("channel is not active!", null, mNettyReceiveListener, DispterMessage.MSG_RECEIVE_FAIL);
            return;
        }
        if (mChannel != null) {
            addReceiveLisenter(mNettyReceiveListener);
            mChannel.writeAndFlush(msg + System.getProperty(NettyConstant.MAG_SEPARATOR_1));
        }
    }

    public void addReceiveLisenter(NettyReceiveListener listener) {
        if (listener != null && !mNettyReceiveListeners.contains(listener)) {
            mNettyReceiveListeners.add(listener);
        }
    }

    public void removeCurrentReceiveLisenter() {
        if (mNettyReceiveListener != null && mNettyReceiveListeners.size() > 0) {
            mNettyReceiveListeners.remove(mNettyReceiveListener);
        }

    }

    public void removeReceiveLisenter(NettyReceiveListener listener) {
        if (listener != null && mNettyReceiveListeners.contains(listener)) {
            mNettyReceiveListeners.remove(listener);
        }
    }

    public void clearReceiveLisenter() {
        mNettyReceiveListeners.clear();
    }

    public void handMsg(String msg) {
        for (NettyReceiveListener listener : mNettyReceiveListeners) {
            if (listener != null) {
                postMsg(msg, null, listener, DispterMessage.MSG_RECEIVE_SUCC);
            }
        }
    }

    public void handErrorMsg(String msg) {
        for (NettyReceiveListener listener : mNettyReceiveListeners) {
            if (listener != null) {
                postMsg(msg, null, listener, DispterMessage.MSG_RECEIVE_FAIL);
            }
        }
    }


    private void postMsg(String msg, NettyConnectListener connectListener, NettyReceiveListener receiveListener, int type) {
        ReplyMessage message = new ReplyMessage();
        message.setConnectListener(connectListener);
        message.setMsg(msg);
        message.setReceiveListener(receiveListener);
        message.setType(type);

        mDispterMessage.handMsg(message);
    }


}

设计的主要类:
1.EventLoopGroup 可以理解为将多个EventLoop进行分组管理的一个类,是EventLoop的一个组。
2.Bootstrap 启动帮助类 参数主要这里配置的
chnnel()
handler() 主要用来接收处理消息 本demo里面用到的是netty自带的一种解码器LineBasedFrameDecoder
option 设置socket相关参数
测试服务端代码:


public class TestServer {

    public static void main(String[] agrs) {
        new TestServer().bind(8080);
    }

    private void bind(int port) {
        EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap(); // (2)
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class) // (3)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast("line", new LineBasedFrameDecoder(1024));
                            pipeline.addLast("decoder", new StringDecoder());
                            pipeline.addLast("encoder", new StringEncoder());
                            pipeline.addLast("handler", new TestServerHandler());
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 1024);


            System.out.println("SimpleChatServer 启动");
            // 绑定端口,开始接收进来的连接
            ChannelFuture f = b.bind(port).sync();
            f.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
            System.out.println("SimpleChatServer 关闭了");
        }

    }
}

TestServerHandler 消息处理器

public class TestServerHandler extends SimpleChannelInboundHandler<String> {
    String TAG_LINE = "line.separator";

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        System.out.println("server receive msg:" + s);
        channelHandlerContext.writeAndFlush("[reply]:" + s + System.getProperty(TAG_LINE));

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
       cause.printStackTrace();
       ctx.close();
    }
}
最后编辑于
?著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,992评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,212评论 3 388
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事?!?“怎么了?”我有些...
    开封第一讲书人阅读 159,535评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,197评论 1 287
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,310评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,383评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,409评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,191评论 0 269
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,621评论 1 306
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,910评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,084评论 1 342
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,763评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,403评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,083评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,318评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,946评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,967评论 2 351