標籤:base 編碼 伺服器端 his png 相互 oop encoding 伺服器ip
1、Netty是什嗎?
本質:JBoss做的一個Jar包
目的:快速開發高效能、高可靠性的網路伺服器和用戶端程式
優點:提供非同步、事件驅動的網路應用程式架構和工具
通俗的說:一個好使的處理Socket的東東
2、Netty的非同步事件驅動模型主要涉及到下面幾個核心的概念
Channel:表示一個與socket關聯的通道
ChannelPipeline: 管道,一個Channel擁有一個ChannelPipeline,ChannelPipeline維護著一個處理鏈(嚴格的說是兩 個:upstream、downstream),處理鏈是由很 多通道處理器ChannelHandler所構成,每個ChannelHandler處理完以 後會傳遞給鏈中的下一個通道處理器繼續處理。
ChannelHandler:通道處理器,使用者可以定義自己的處理控制代碼來處理每個請求,或發出請求前進行預先處理,典型的有編碼/解碼器:decoder、encoder。
ChannelEvent:事件,是整個模型的處理對象,當產生或觸發(fire)一個事件時,該事件會沿著ChannelPipeline處理鏈依次被處理。 ChannelFuture: 非同步結果,這個是非同步事件處理的關鍵,當一個事件被處理時,可以直接以ChannelFuture的形式直接返回,不用在當前操作中被阻塞。可以通過 ChannelFuture得到最終的執行結果,具體的做法是在ChannelFuture添加監聽器listener,當操作最終被執行完 後,listener會被觸發,我們可以在listener的回呼函數中預定義我們的業務代碼。
ChannelPipeline實際上維持了兩個處理鏈:upstream、downstream。 Upstream一般處理來自Channel的讀事件,而downstream一般處理向Channel的寫事件。需要注意的是,這兩個處理鏈是相互獨立 的,在upstream鏈中傳遞到最後一個ChannelHandler處理後,不會再傳遞到downstream鏈中繼續處理。
在downstream鏈的末端會有個ChannelSink處理,使用者可以自訂這個ChannelSink的實現,系統也有個預設的實現,當downstream鏈中最後一個ChannelHandler處理完後會被傳遞給這個ChannelSink進行最後的處理。
3、Demo
3.1、NettyServer.java
package com.jacky.server;import java.util.concurrent.TimeUnit;import org.apache.log4j.Logger;import io.netty.bootstrap.ServerBootstrap;import io.netty.channel.ChannelFuture;import io.netty.channel.ChannelInitializer;import io.netty.channel.ChannelOption;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.LengthFieldBasedFrameDecoder;import io.netty.handler.timeout.IdleStateHandler;public class NettyServer { private static Logger logger = Logger.getLogger(NettyServer.class); private int port; public NettyServer(int port) { this.port = port; bind(); } private void bind() { EventLoopGroup boss = new NioEventLoopGroup(); EventLoopGroup worker = new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(boss, worker); bootstrap.channel(NioServerSocketChannel.class); bootstrap.option(ChannelOption.SO_BACKLOG, 1024); //串連數 bootstrap.option(ChannelOption.TCP_NODELAY, true); //不延遲,訊息立即發送 bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true); //長串連 bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { ChannelPipeline p = socketChannel.pipeline(); p.addLast(new NettyServerHandler()); } }); ChannelFuture f = bootstrap.bind(port).sync(); if (f.isSuccess()) { logger.debug("啟動Netty服務成功,連接埠號碼:" + this.port); } // 關閉串連 f.channel().closeFuture().sync(); } catch (Exception e) { logger.error("啟動Netty服務異常,異常資訊:" + e.getMessage()); e.printStackTrace(); } finally { boss.shutdownGracefully(); worker.shutdownGracefully(); } } public static void main(String[] args) throws InterruptedException { NettyServer server= new NettyServer(9999); }}
3.2、NettyServerHandler.java
package com.jacky.server;import java.io.UnsupportedEncodingException;import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelHandlerAdapter;import io.netty.channel.ChannelHandlerContext;public class NettyServerHandler extends ChannelHandlerAdapter { @Override public void channelRead(ChannelHandlerContext context, Object msg) { ByteBuf buf = (ByteBuf) msg; String recieved = getMessage(buf); System.out.println("伺服器接收到訊息:" + recieved); try { context.writeAndFlush(getSendByteBuf("APPLE")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } /* * 從ByteBuf中擷取資訊 使用UTF-8編碼返回 */ 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; } } private ByteBuf getSendByteBuf(String message) throws UnsupportedEncodingException { byte[] req = message.getBytes("UTF-8"); ByteBuf pingMessage = Unpooled.buffer(); pingMessage.writeBytes(req); return pingMessage; }}
3.3、NettyClient.java
package com.jacky.client;import java.util.concurrent.TimeUnit;import io.netty.bootstrap.Bootstrap;import io.netty.channel.ChannelFuture;import io.netty.channel.ChannelInitializer;import io.netty.channel.ChannelOption;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.LengthFieldBasedFrameDecoder;import io.netty.handler.timeout.IdleStateHandler;public class NettyClient { /* * 伺服器連接埠號碼 */ private int port; /* * 伺服器IP */ private String host; public NettyClient(int port, String host) throws InterruptedException { this.port = port; this.host = host; start(); } private void start() throws InterruptedException { EventLoopGroup eventLoopGroup = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); bootstrap.channel(NioSocketChannel.class); bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.group(eventLoopGroup); bootstrap.remoteAddress(host, port); bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast(new NettyClientHandler()); } }); ChannelFuture future = bootstrap.connect(host, port).sync(); if (future.isSuccess()) { SocketChannel socketChannel = (SocketChannel) future.channel(); System.out.println("----------------connect server success----------------"); } future.channel().closeFuture().sync(); } finally { eventLoopGroup.shutdownGracefully(); } } public static void main(String[] args) throws InterruptedException { NettyClient client = new NettyClient(9999, "localhost"); }}
3.4、NettyClientHandler.java
package com.jacky.client;import java.io.UnsupportedEncodingException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.concurrent.TimeUnit;import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelHandlerAdapter;import io.netty.channel.ChannelHandlerContext;public class NettyClientHandler extends ChannelHandlerAdapter { private ByteBuf firstMessage; @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { byte[] data = "伺服器,給我一個APPLE".getBytes(); firstMessage=Unpooled.buffer(); firstMessage.writeBytes(data); ctx.writeAndFlush(firstMessage); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 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; } }}
netty5入門教程0