Netty通信框架Java实现小记
生活随笔
收集整理的這篇文章主要介紹了
Netty通信框架Java实现小记
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1、Netty介紹
? ?Netty通俗地說就是一套Socket通信框架,提供異步的、事件驅動的網(wǎng)絡應用程序框架和工具,可快速開發(fā)高性能、高可靠性的網(wǎng)絡服務器和客戶端程序
2、Netty的特性
? ?1)設計
? ? ? 統(tǒng)一的API,適用于不同的協(xié)議(阻塞和非阻塞)
? ? ? 基于靈活、可擴展的事件驅動模型
? ? ? 高度可定制的線程模型
? ? ? 可靠的無連接數(shù)據(jù)Socket支持(UDP)
? ?2)性能
? ? ? 更好的吞吐量,低延遲
? ? ? 更省資源
? ? ? 盡量減少不必要的內(nèi)存拷貝
? ?3)安全
? ? ? 完整的SSL/TLS和STARTTLS的支持
? ? ? 能在Applet與Android的限制環(huán)境運行良好
? ?4)健壯性
? ? ? 不再因過快、過慢或超負載連接導致OutOfMemoryError
? ? ? 不再有在高速網(wǎng)絡環(huán)境下NIO讀寫頻率不一致的問題
? ?5)易用
? ? ? 完善的JavaDoc,用戶指南和樣例
? ? ? 簡潔簡單
3、下載Jar包
? ? http://netty.io/downloads.html 下載
? ? 引入netty-all-4.1.4.Final.jar包到工程
4、Server端代碼示例:
?? package cn.netty;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;public class NettyServer {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); //連接數(shù)bootstrap.option(ChannelOption.TCP_NODELAY, true); //不延遲,消息立即發(fā)送bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true); //長連接bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel socketChannel) throws Exception {ChannelPipeline p = socketChannel.pipeline();p.addLast(new NettyServerHandler());} });ChannelFuture f = bootstrap.bind(port).sync();if (f.isSuccess()) {System.out.println("啟動Netty服務成功,端口號:" + this.port);}//Wait until the server socket is closed.f.channel().closeFuture().sync();} catch (Exception e) {System.out.println("啟動Netty服務異常,異常信息:" + e.getMessage());e.printStackTrace();} finally {boss.shutdownGracefully();worker.shutdownGracefully();}}public static void main(String[] args) throws InterruptedException {NettyServer server= new NettyServer(9999);} } package cn.netty;import java.io.UnsupportedEncodingException; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter;public class NettyServerHandler extends ChannelInboundHandlerAdapter {@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) {ByteBuf buf = (ByteBuf) msg; String recieved = getMessage(buf);System.out.println("服務器接收到消息:" + recieved); try {ctx.writeAndFlush(getSendByteBuf("Message"));} 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;} }5、Client端代碼示例:
package cn.netty;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;public class NettyClient {private int port;//服務器端口號private String host;//服務器IPpublic 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>() {@Overrideprotected 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----------------");}// Wait until the connection is closed.future.channel().closeFuture().sync();} finally {eventLoopGroup.shutdownGracefully();}}public static void main(String[] args) throws InterruptedException {NettyClient client = new NettyClient(9999,"localhost");} }
package cn.netty;import java.io.UnsupportedEncodingException; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter;public class NettyClientHandler extends ChannelInboundHandlerAdapter {private ByteBuf firstMessage;@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {byte[] data = "服務器,給我一個Message".getBytes();firstMessage=Unpooled.buffer();firstMessage.writeBytes(data);ctx.writeAndFlush(firstMessage);}@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {ByteBuf buf = (ByteBuf) msg;String rev = getMessage(buf);System.out.println("客戶端收到服務器數(shù)據(jù):" + 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;}}}
6、總結:server和client端主要是建立連接,數(shù)據(jù)接收和發(fā)送主要是繼承ChannelInboundHandlerAdapter類,重載channelRead等函數(shù)。
? ?Netty通俗地說就是一套Socket通信框架,提供異步的、事件驅動的網(wǎng)絡應用程序框架和工具,可快速開發(fā)高性能、高可靠性的網(wǎng)絡服務器和客戶端程序
2、Netty的特性
? ?1)設計
? ? ? 統(tǒng)一的API,適用于不同的協(xié)議(阻塞和非阻塞)
? ? ? 基于靈活、可擴展的事件驅動模型
? ? ? 高度可定制的線程模型
? ? ? 可靠的無連接數(shù)據(jù)Socket支持(UDP)
? ?2)性能
? ? ? 更好的吞吐量,低延遲
? ? ? 更省資源
? ? ? 盡量減少不必要的內(nèi)存拷貝
? ?3)安全
? ? ? 完整的SSL/TLS和STARTTLS的支持
? ? ? 能在Applet與Android的限制環(huán)境運行良好
? ?4)健壯性
? ? ? 不再因過快、過慢或超負載連接導致OutOfMemoryError
? ? ? 不再有在高速網(wǎng)絡環(huán)境下NIO讀寫頻率不一致的問題
? ?5)易用
? ? ? 完善的JavaDoc,用戶指南和樣例
? ? ? 簡潔簡單
3、下載Jar包
? ? http://netty.io/downloads.html 下載
? ? 引入netty-all-4.1.4.Final.jar包到工程
4、Server端代碼示例:
?? package cn.netty;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;public class NettyServer {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); //連接數(shù)bootstrap.option(ChannelOption.TCP_NODELAY, true); //不延遲,消息立即發(fā)送bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true); //長連接bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel socketChannel) throws Exception {ChannelPipeline p = socketChannel.pipeline();p.addLast(new NettyServerHandler());} });ChannelFuture f = bootstrap.bind(port).sync();if (f.isSuccess()) {System.out.println("啟動Netty服務成功,端口號:" + this.port);}//Wait until the server socket is closed.f.channel().closeFuture().sync();} catch (Exception e) {System.out.println("啟動Netty服務異常,異常信息:" + e.getMessage());e.printStackTrace();} finally {boss.shutdownGracefully();worker.shutdownGracefully();}}public static void main(String[] args) throws InterruptedException {NettyServer server= new NettyServer(9999);} } package cn.netty;import java.io.UnsupportedEncodingException; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter;public class NettyServerHandler extends ChannelInboundHandlerAdapter {@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) {ByteBuf buf = (ByteBuf) msg; String recieved = getMessage(buf);System.out.println("服務器接收到消息:" + recieved); try {ctx.writeAndFlush(getSendByteBuf("Message"));} 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;} }5、Client端代碼示例:
package cn.netty;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;public class NettyClient {private int port;//服務器端口號private String host;//服務器IPpublic 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>() {@Overrideprotected 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----------------");}// Wait until the connection is closed.future.channel().closeFuture().sync();} finally {eventLoopGroup.shutdownGracefully();}}public static void main(String[] args) throws InterruptedException {NettyClient client = new NettyClient(9999,"localhost");} }
package cn.netty;import java.io.UnsupportedEncodingException; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter;public class NettyClientHandler extends ChannelInboundHandlerAdapter {private ByteBuf firstMessage;@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {byte[] data = "服務器,給我一個Message".getBytes();firstMessage=Unpooled.buffer();firstMessage.writeBytes(data);ctx.writeAndFlush(firstMessage);}@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {ByteBuf buf = (ByteBuf) msg;String rev = getMessage(buf);System.out.println("客戶端收到服務器數(shù)據(jù):" + 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;}}}
6、總結:server和client端主要是建立連接,數(shù)據(jù)接收和發(fā)送主要是繼承ChannelInboundHandlerAdapter類,重載channelRead等函數(shù)。
總結
以上是生活随笔為你收集整理的Netty通信框架Java实现小记的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Ansj中文分词Java开发小记
- 下一篇: Java图片文本识别工具Eye实现(不支