您好,登錄后才能下訂單哦!
Netty 是一個基于 JAVA NIO 類庫的異步通信框架,它的架構特點是:異步非阻塞、基于事件驅動、高性能、高可靠性和高可定制性。換句話說,Netty是一個NIO框架,使用它可以簡單快速地開發網絡應用程序,比如客戶端和服務端的協議。Netty大大簡化了網絡程序的開發過程比如TCP和UDP的 Socket的開發。Netty 已逐漸成為 Java NIO 編程的首選框架。
項目官方地址:http://netty.io/index.html
API 使用簡單,開發門檻低;
功能強大,預置了多種編解碼功能,支持多種主流協議;
定制能力強,可以通過 ChannelHandler 對通信框架進行靈活的擴展;
性能高,通過與其它業界主流的 NIO 框架對比,Netty 的綜合性能最優;
社區活躍,版本迭代周期短,發現的 BUG 可以被及時修復,同時,更多的新功能會被加入;
經歷了大規模的商業應用考驗,質量得到驗證。在互聯網、大數據、網絡游戲、企業應用、電信軟件等眾多行業得到成功商用,證明了它完全滿足不同行業的商用標準。
添加pom依賴
Pom代碼
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.0.Final</version>
</dependency>
SimpleServer(服務端)
Java代碼
package com.yingjun.netty.server;
import io.netty.bootstrap.ServerBootstrap;
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.NioServerSocketChannel;
/**
*
* Netty中,通訊的雙方建立連接后,會把數據按照ByteBuf的方式進行傳輸,
* 例如http協議中,就是通過HttpRequestDecoder對ByteBuf數據流進行處理,轉換成http的對象。
*
*/
public class SimpleServer {
private int port;
public SimpleServer(int port) {
this.port = port;
}
public void run() throws Exception {
//EventLoopGroup是用來處理IO操作的多線程事件循環器
//bossGroup 用來接收進來的連接
EventLoopGroup bossGroup = new NioEventLoopGroup();
//workerGroup 用來處理已經被接收的連接
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
//啟動 NIO 服務的輔助啟動類
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
//配置 Channel
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
// 注冊handler
ch.pipeline().addLast(new SimpleServerHandler());
}
})
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
// 綁定端口,開始接收進來的連接
ChannelFuture f = b.bind(port).sync();
// 等待服務器 socket 關閉 。
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
new SimpleServer(9999).run();
}
}
SimpleServerHandler(服務端請求處理Handler)
Java代碼
package com.yingjun.netty.server;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
public class SimpleServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("SimpleServerHandler.channelRead");
ByteBuf result = (ByteBuf) msg;
byte[] result1 = new byte[result.readableBytes()];
// msg中存儲的是ByteBuf類型的數據,把數據讀取到byte[]中
result.readBytes(result1);
String resultStr = new String(result1);
// 接收并打印客戶端的信息
System.out.println("Client said:" + resultStr);
// 釋放資源,這行很關鍵
result.release();
// 向客戶端發送消息
String response = "hello client!";
// 在當前場景下,發送的數據必須轉換成ByteBuf數組
ByteBuf encoded = ctx.alloc().buffer(4 * response.length());
encoded.writeBytes(response.getBytes());
ctx.write(encoded);
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// 當出現異常就關閉連接
cause.printStackTrace();
ctx.close();
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
}
SimpleServer(客戶端)
Java代碼
package com.yingjun.netty.server;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
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.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
public class SimpleClient {
public void connect(String host, int port) throws Exception {
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(workerGroup);
b.channel(NioSocketChannel.class);
b.option(ChannelOption.SO_KEEPALIVE, true);
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new SimpleClientHandler());
}
});
// Start the client.
ChannelFuture f = b.connect(host, port).sync();
// Wait until the connection is closed.
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
SimpleClient client=new SimpleClient();
client.connect("127.0.0.1", 9999);
}
}
SimpleServerHandler(客戶端請求處理Handler springmvc+mybatis+spring 整合 下載地址 )
Java代碼
package com.yingjun.netty.server;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
public class SimpleClientHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("SimpleClientHandler.channelRead");
ByteBuf result = (ByteBuf) msg;
byte[] result1 = new byte[result.readableBytes()];
result.readBytes(result1);
System.out.println("Server said:" + new String(result1));
result.release();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// 當出現異常就關閉連接
cause.printStackTrace();
ctx.close();
}
// 連接成功后,向server發送消息
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
String msg = "hello Server!";
ByteBuf encoded = ctx.alloc().buffer(4 * msg.length());
encoded.writeBytes(msg.getBytes());
ctx.write(encoded);
ctx.flush();
}
}
運行結果:
Java代碼
SimpleClientHandler.channelRead
Server said:hello client!
------------------------------------------
SimpleServerHandler.channelRead
Client said:hello Server!
SimpleServerHandler.channelRead
Client said:hello Server!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。