美文网首页
Netty-server

Netty-server

作者: 冯杰宁 | 来源:发表于2018-07-26 17:19 被阅读0次

    第一讲:服务端    

        当然网上对Netty 这框架有许多人都介绍,对于在网络编程的地位以及优劣性也有很多,打架可以去看看,今天我主要的目的是将自己项目中的实例拿出来和打架风向

     简单的提一嘴:Netty 是一个 NIO client-server(客户端服务器)框架,使用 Netty 可以快速开发网络应用,例如服务器和客户 端协议。 Netty 提供了一种新的方式来使开发网络应用程序,这种新的方式使得它很容易使用和有很强的扩展性。 Netty 的内部实现时很复杂的,但是 Netty 提供了简单易用的 api 从网络处理代码中解耦业务逻辑。 Netty 是完全基 于 NIO 实现的,所以整个 Netty 都是异步的。

    public class BaseClient implements Runnable { 

     private String host_; private int port_; private int reConnectCount_ = 0; 

     private DefinedHandler definedHandler_; 

     private OnMessageListener messageListener_; 

     private OnStartupListener startupListener_; 

     private volatile boolean isChannelPrepared_; //拆包长度

     private final static int MAX_MESSAGE_LENGTH = 8192; 

     public BaseClient(String host, int port, OnMessageListener messageListener, OnStartupListener startupListener) { 

     host_ = host; 

     port_ = port;

     messageListener_ = messageListener; startupListener_ = startupListener; 

     } 

     //建立连接 public void connect(String host,int port) {

     EventLoopGroup group = new NioEventLoopGroup();

     try { 

     Bootstrap b = new Bootstrap(); b.group(group) // 注册线程池 

     b.channel(NioSocketChannel.class) // 使用NioSocketChannel来作为连接用的channel类

     .remoteAddress(new InetSocketAddress(host, port)) // 绑定连接端口和host信息

     .handler(new ChannelInitializer() { // 绑定连接初始化器 

     @Override protected void initChannel(SocketChannel ch) throws Exception { 

     System.out.println("connected..."); /

     ByteBuf delimiter = Unpooled.copiedBuffer("_#_".getBytes()); // 增加 DelimiterBasedFrameDecoder编码器 ch.pipeline().addLast(new DelimiterBasedFrameDecoder(MAX_MESSAGE_LENGTH, delimiter)); //

    ch.pipeline().addLast(new DelimiterBasedFrameDecoder(MAX_MESSAGE_LENGTH, Delimiters.lineDelimiter())); //字符串解码器 

     ch.pipeline().addLast(new StringDecoder(Charset.forName("UTF-8"))); //字符串解码器 

     ch.pipeline().addLast(new StringEncoder(Charset.forName("UTF-8"))); 

     //自定 处理器

     definedHandler_ = new DefinedHandler(messageListener_); //上面

     ch.pipeline().addLast(definedHandler_); 

     } }); 

     System.out.println("created..");

    /ChannelFuture cf = b.connect().sync(); // 异步连接服务器

     System.out.println("connected..."); // 连接完成 cf.channel().closeFuture().sync(); // 异步等待关闭连接channel System.out.println("closed.."); // 关闭完成*/ ChannelFuture f = b.connect(host, port).sync(); f.addListener(new GenericFutureListener>() {

                    @Override

                    public void operationComplete(Future future) throws Exception {

                        if (future.isSuccess()) {

                            reConnectCount_ = 0;

                            isChannelPrepared_ = true;

                            startupListener_.onCompletion(true);

                            System.out.println("1与服务器{}:{}连接建立成功..."+host_+ port_);

                        } else {

                            isChannelPrepared_ = false;

                            startupListener_.onCompletion(false);

                            System.out.println("1与服务器{}:{}连接建立失败..."+ host_+ port_);

                        }

                    }

                });

                f.channel().closeFuture().sync();

            } catch (Exception e) {

                isChannelPrepared_ = false;

                System.err.println("3与服务器{}:{}连接出现异常...");

            } finally {

                isChannelPrepared_ = false;

                group.shutdownGracefully();

                reConnect(host, port);

            }

        }

        @Override

        public void run() {

            connect(host_, port_);

        }

        // 断线重连

        private void reConnect(String host, int port) {

            // fixme: 重连显式退出?

            try {

                isChannelPrepared_ = false;

                int delay = ++reConnectCount_ * 5;

                reConnectCount_ = reConnectCount_ > 23 ? 23 : reConnectCount_;

                System.err.println("2与服务器{}:{}连接已断开, {}秒后重连..."+ host+ port+ delay);

                Thread.sleep(delay * 1000);

                connect(host, port);

            } catch (Exception e) {

                e.printStackTrace();

            }

        }

    }

    相关文章

      网友评论

          本文标题:Netty-server

          本文链接:https://www.haomeiwen.com/subject/yggbmftx.html