在文章開始之前首先明確一個問題,為什么要使用Netty,Netty解決了什么問題,圍繞著這個問題我們開始本篇文章的學(xué)習(xí)
- 為什么要使用Netty
netty它是對jdk中nio模塊的封裝,你也可以不使用Netty,就像開發(fā)網(wǎng)站可以只使用Servlet+jsp一樣。結(jié)果是效率低且Bug多 - Netty解決了什么問題
沿用知乎上的答案
jdk強(qiáng)迫你必須用socket來寫服務(wù)器,實際上是很繁瑣的。缺乏一個高層次的api。
netty說,我來寫jdk的socket,并給你一個新的更簡潔的api,你傻瓜式的就能寫好一個網(wǎng)絡(luò)服務(wù)器(而且是event-driven/proactor/reactor等等)。
當(dāng)然,netty通過jni,引入了epoll這樣的linux系統(tǒng)調(diào)用,使得它不單單是jdk的一個簡單包裹,的確也加了些東西進(jìn)去
想深入了解Netty的應(yīng)用場景和優(yōu)勢可以參考知乎上的問答知乎傳送門
按照我的講解風(fēng)格,先運(yùn)行代碼,跑起來再問為什么
- 導(dǎo)入依賴
本項目使用的是Gradle,下載Jar包的速度慢,可以配置阿里云的倉庫
/* repositories {
maven {url 'http://maven.aliyun.com/nexus/content/groups/public/'}
mavenLocal()
mavenCentral()
}*/
compile (group: 'io.netty', name: 'netty-all', version: '4.1.25.Final')
- 編寫服務(wù)器端
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
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;
import io.netty.handler.codec.string.StringDecoder;
import java.net.InetSocketAddress;
/**
* @author tanoak@qq.com
* @date 2018/6/26 22:46
* @Desc
*/
public class NettyServer {
// 端口號
private final int port;
public NettyServer(int port) {
this.port = port;
}
public void start() throws Exception {
ServerBootstrap serverBootstrap = new ServerBootstrap();//① 是一個啟動NIO服務(wù)的輔助啟動類
NioEventLoopGroup worker = new NioEventLoopGroup();//②NioEventLoopGroup是用來處理IO操作的多線程事件循環(huán)器
serverBootstrap
.group(worker)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) {
ch.pipeline().addLast(new StringDecoder());
ch.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
//讀取客戶端發(fā)送的消息
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) {
System.out.println("【客戶端發(fā)送的消息】"+msg);
}
});
}
})
.bind(port);
}
public static void main(String[] args) throws Exception {
try {
new NettyServer( 8088).start();
System.out.println("啟動成功");
}catch (Exception e){
System.out.println("啟動失敗");
}
}
}
- 客戶端
import com.tanoak.demo1.client.EchoClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
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.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import java.net.InetSocketAddress;
import java.time.LocalDateTime;
import java.util.Date;
/**
* @author tanoak@qq.com
* @date 2018/6/25 0:46
* @Desc
*/
public class NettyClient {
private final String host;
private final int port;
public NettyClient(String host, int port) {
this.host = host;
this.port = port;
}
public void start() throws Exception {
Bootstrap bootstrap = new Bootstrap();
NioEventLoopGroup group = new NioEventLoopGroup();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) {
ch.pipeline().addLast(new StringEncoder());
}
});
Channel channel = bootstrap.connect(host, port).channel();
while (true) {
channel.writeAndFlush("現(xiàn)在時間:"+LocalDateTime.now());
Thread.sleep(2000);
}
}
public static void main(String[] args) throws Exception {
new NettyClient("127.0.0.1",8088 ).start();
}
}
代碼運(yùn)行OK后我們接下來看下服務(wù)器端它所做的工作
-
創(chuàng)建ServerBootstrap對象以及 NioEventLoopGroup 對象 。然后進(jìn)行優(yōu)雅的鏈?zhǔn)秸{(diào)用,這里看一下group(worker)這個方法的源碼
group()方法進(jìn)行了重載,接著就是channel()方法添加一個NioServerSocketChannel的類,然后childHandler()上 目的是添加handler,用來監(jiān)聽已經(jīng)連接的客戶端的Channel的動作和狀態(tài),childHandler會在客戶端成功connect后執(zhí)行
接下來我們來看下客戶端的工作
重復(fù)步驟省略直接看連接服務(wù)器的代碼 bootstrap.connect(),接著就是利用channel 對象向服務(wù)器端寫入數(shù)據(jù)
至此一個簡單的Demo就完成了,如講解有誤,請指正,本篇參考《Netty實戰(zhàn)》這本書,這本書個人極力推薦,想了解Netty的可以考慮入門一本
