初学Netty(杰哥好久不见)
生活随笔
收集整理的這篇文章主要介紹了
初学Netty(杰哥好久不见)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、我對Netty的理解:
一個開發網絡編程的框架,改善了NIO框架的缺點。
二、第一個netty小程序
1.服務器啟動類ServerBootstrap:在該類中配置服務器連接數,是否延遲,長連接?添加數據操作類等等
1 1.定義一個端口 2 *2.在該類構造方法中傳入端口參數,并在該類構造時調用bind()方法初始化服務器端配置 3 *3.在bind()方法中先實例兩個EventLoopGroup(boss和worker)用來管理線程----- 4 * EventLoopGroup boss = new NioEventLoopGroup(); 5 EventLoopGroup worker = new NioEventLoopGroup(); 6 4.使用ServerBootstrap類來初始化netty服務器,并且開始監聽端口的socket請求 7 ServerBootstrap bootstrap = new ServerBootstrap(); 8 5.根據ServerBootstrap內封裝好的方法設置服務器基礎信息 9 bootstrap.group(boss, worker);//boss和worker兩個線程池 10 bootstrap.channel(NioServerSocketChannel.class); 11 bootstrap.option(ChannelOption.SO_BACKLOG, 1024); // 連接數 12 bootstrap.option(ChannelOption.TCP_NODELAY, true); // 不延遲,消息立即發送 13 bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true); // 長連接 14 bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { 15 @Override 16 protected void initChannel(SocketChannel socketChannel) throws Exception { 17 ChannelPipeline p = socketChannel.pipeline();創建Channel通道 18 p.addLast(new NettyServerHandler()); //往通道中添加i/o事件處理類 19 } 20 }); 21 6.配置好服務器,在服務器啟動時綁定闖入的port端口,等待同步 22 ChannelFuture f = bootstrap.bind(port).sync(); 23 7.如果綁定成功 24 if(f.isSuccess()){ 25 26 } 27 f.channel().closeFuture().sync(); 28 8.優雅釋放 29 boss.shutdownGracefully(); 30 worker.shutdownGracefully();
這樣服務器端啟動類就寫好了,接下來寫服務器端對客戶端發來數據的操作類
2.數據操作類ServerHandler:在該類中對客戶端發來的數據進行操作,發送給客戶端數據
* 1.繼承ChannelHandlerAdapter,重寫channelRead方法* @Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) {* 2.channelRead方法中的msg參數(服務器接收到的客戶端發送的消息)強制轉換成ByteBuf類型* ByteBuf buf = (ByteBuf) msg;* 3.寫一個getMessage(ByteBuf xx)方法(返回String),在該方法中:* ---首先通過ByteBuf類的readBytes()方法將msg轉換成字節數組* byte[] con = new byte[buf.readableBytes()];buf.readBytes(con);---返回String,指定編碼(有可能出現不支持的編碼類型異常,所以要trycatch)new String(con,"UTF-8");4.對已經轉換成String類型的數據進行操作System.out.println("服務器接收到消息:" + recieved);* 5.服務端往客戶端發送數據(數據類型ByteBuf)* try {ctx.writeAndFlush(getSendByteBuf("APPLE"));} catch (UnsupportedEncodingException e) {e.printStackTrace();}6. getSendByteBuf(String xxx)方法將服務端發送的數據轉換成ByteBuf類型byte[] req = message.getBytes("UTF-8");ByteBuf pingMessage = Unpooled.buffer();pingMessage.writeBytes(req);return pingMessage;*/
以上兩步就完成了對Netty服務器端的基本配置,接下來編寫客戶端代碼,首先是客戶端啟動類
3.ClientBootstrap,跟第一步寫ServerBootstrap類類似
*1.定義兩個變量:客戶端端口號和服務器IP地址*2.在構造方法中傳入這兩個參數,在該類構造的同時啟動start()方法(start()方法要拋出線程中斷異常)*3.在start()方法中實例客戶端線程對象* EventLoopGroup eventLoopGroup = new NioEventLoopGroup();4.實例客戶端啟動類:BootstrapBootstrap bootstrap = new Bootstrap();對啟動信息進行配置:bootstrap.channel(NioSocketChannel.class);bootstrap.group(eventLoopGroup);bootstrap.option(ChannelOption.SO_KEEPALIVE, true);//長連接bootstrap.remoteAddress(host, port);//服務器主機地址端口號bootstrap.handler(new ChannelInitializer<SocketChannel>() {//添加客戶端數據處理類@Overrideprotected void initChannel(SocketChannel socketChannel)throws Exception { socketChannel.pipeline().addLast(new NettyClientHandler());}});5.在客戶端啟動時連接服務器ip和端口ChannelFuture cf = bootstrap.connect(host,port).sync();6.如果連接成功if(cf.isSuccess()){}7.關閉通道cf.channel.closeFuture().sync();8.優雅釋放eventLoopGroup.shutdownGracefully();*/
4.最后寫客戶端數據操作類,ClientHandler
*1.首先跟服務器操作類一樣繼承ChannelHandlerAdapter類,重寫channelRead和channelActive兩個方法*其中channelActive方法是用來發送客戶端信息的,channelRead方法客戶端是接收服務器數據的*2.先聲明一個全局變量firstMessage,用來接收客戶端發出去的信息的值*3.在channelActive方法中把要傳輸的數據轉化為字節數組* byte[] data = "服務器,給我一個APPLE".getBytes();* firstMessage = Unpooled.buffer();firstMessage.writeBytes(data);* ctx.writeAndFlush(firstMessage);*4.在channelRead方法中* ByteBuf buf = (ByteBuf) msg;String rev = getMessage(buf);System.out.println("客戶端收到服務器數據:" + rev);}private String getMessage(ByteBuf buf) {byte[] con = new byte[buf.readableBytes()];buf.readBytes(con);try {return new String(con, "UTF-8");} catch (UnsupportedEncodingException e) {e.printStackTrace();return null;}}*/
ok,第一個netty程序完成
?
轉載于:https://www.cnblogs.com/qiuhx/p/6400972.html
總結
以上是生活随笔為你收集整理的初学Netty(杰哥好久不见)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ---Mybatis3学习笔记(2)
- 下一篇: java 服务端客户端数据传输出现乱码