netty客户端实现

239 阅读2分钟

一、Netty简介

Netty是一个基于JAVA NIO 类库的异步通信框架,它的架构特点是:异步非阻塞、基于事件驱动、高性能、高可靠性和高可定制性。换句话说,Netty是一个NIO框架,使用它可以简单快速地开发网络应用程序,比如客户端和服务端的协议。Netty大大简化了网络程序的开发过程比如TCP和UDP的 Socket的开发。Netty 已逐渐成为 Java NIO 编程的首选框架。

二、什么是物联网?

nio通信框架

三、物联网主要运用到Netty哪些特性?

1、TCP长连接 2、能够和各种序列化框架完美整合

四、为什么要使用Netty,相对于其他通信框架mina有哪些优点

1、API使用简单,开发门槛低 2、功能强大,预置了多种编解码功能,支持多种主流协议 3、社区活跃,版本更新快 4、技术稳定可靠,如:elasticsearch、spark、dubbo、motan等开源框架底层通信采用的是netty

五、Netty客户端编写

第一步,连接到服务端 第二步,向服务端发送数据 第三步,处理服务端返回的数据 第四步,关闭连接

import com.alibaba.fastjson.JSONObject;
import com.dxfx.user.model.User;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.AttributeKey;

/**
 * Netty客户端编写
 * @author ouyangfeng
 *
 */
public class NettyClient {
    
    public static void main(String[] args) throws InterruptedException {
        // 首先,netty通过ServerBootstrap启动服务端
        Bootstrap client = new Bootstrap();
        
        //第1步 定义线程组,处理读写和链接事件,没有了accept事件
        EventLoopGroup group = new NioEventLoopGroup();
        client.group(group );
        
        //第2步 绑定客户端通道
        client.channel(NioSocketChannel.class);
        
        //第3步 给NIoSocketChannel初始化handler, 处理读写事件
        client.handler(new ChannelInitializer<NioSocketChannel>() {  //通道是NioSocketChannel
            @Override
            protected void initChannel(NioSocketChannel ch) throws Exception {
                //字符串编码器,一定要加在SimpleClientHandler 的上面
                ch.pipeline().addLast(new StringEncoder());
                ch.pipeline().addLast(new DelimiterBasedFrameDecoder(   
                        Integer.MAX_VALUE, Delimiters.lineDelimiter()[0])); 
                //找到他的管道 增加他的handler
                ch.pipeline().addLast(new SimpleClientHandler());
            }
        });
        
        //连接服务器
        ChannelFuture future = client.connect("localhost", 8080).sync();
        
        //发送数据给服务器
        User user = new User();
        user.setAge(12);
        user.setId(1);
        user.setName("sssss");
        future.channel().writeAndFlush(JSONObject.toJSONString(user)+"\r\n");
        
        for(int i=0;i<5;i++){
            String msg = "ssss"+i+"\r\n";
            future.channel().writeAndFlush(msg);
        }
        
        //当通道关闭了,就继续往下走
        future.channel().closeFuture().sync();
        
        //接收服务端返回的数据
        AttributeKey<String> key = AttributeKey.valueOf("ServerData");
        Object result = future.channel().attr(key).get();
        System.out.println(result.toString());
    }

}
import java.nio.charset.Charset;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.AttributeKey;

/**
 * 处理服务端返回的数据
 * 
 * @author ouyangfeng
 *
 */
public class SimpleClientHandler extends ChannelInboundHandlerAdapter {
 
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof ByteBuf) {
            String value = ((ByteBuf) msg).toString(Charset.defaultCharset());
            System.out.println("服务器端返回的数据:" + value);
        }
         
        AttributeKey<String> key = AttributeKey.valueOf("ServerData");
        ctx.channel().attr(key).set("客户端处理完毕");

        //把客户端的通道关闭
        ctx.channel().close();
    }

}

六、Netty客户端输出的信息

服务器端返回的数据:hello client 客户端处理完毕 服务器端返回的数据:hello client 服务器端返回的数据:hello client 服务器端返回的数据:hello client 服务器端返回的数据:hello client 服务器端返回的数据:hello client