今天分享一下netty的helloworld,簡單容易上手。
首先看server(注釋已在代碼中標(biāo)明)
package com.netty.test;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class Server {
public static void main(String[] args) throws InterruptedException {
//用來接收客戶端傳進來的連接
NioEventLoopGroup boss = new NioEventLoopGroup();
//用來處理已被接收的連接
NioEventLoopGroup work = new NioEventLoopGroup();
//輔助類 用于幫助我們創(chuàng)建netty服務(wù)
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(boss, work)
.channel(NioServerSocketChannel.class)//設(shè)置NIO模式
.option(ChannelOption.SO_BACKLOG, 1024)//設(shè)置tcp緩沖區(qū)
.childOption(ChannelOption.SO_SNDBUF, 32*1024)//設(shè)置發(fā)送緩沖區(qū)數(shù)據(jù)大小
.option(ChannelOption.SO_RCVBUF, 32*1024)//設(shè)置接收緩沖區(qū)數(shù)據(jù)大小
.childOption(ChannelOption.SO_KEEPALIVE, true)//保持長連接
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//通道的初始化,數(shù)據(jù)傳輸過來進行攔截及執(zhí)行
ch.pipeline().addLast(new ServerHandler());
}
});
ChannelFuture f = serverBootstrap.bind(8888).sync();//綁定端口啟動服務(wù)
f.channel().closeFuture().sync();
work.shutdownGracefully();
boss.shutdownGracefully();
}
}
接下來在看數(shù)據(jù)攔截的handler,這個里邊主要是進行數(shù)據(jù)的處理。
package com.netty.test;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
public class ServerHandler extends ChannelInboundHandlerAdapter{
/**
* 通道激活
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("數(shù)據(jù)激活");
}
/**
* 通道數(shù)據(jù)讀取
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf in = (ByteBuf) msg;
byte [] by = new byte [in.readableBytes()];
in.readBytes(by);
String body=new String(by,"utf-8");
System.out.println("服務(wù)器收到數(shù)據(jù):"+body);
String response="進行返回給客戶端的響應(yīng)"+body;
ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
System.out.println("數(shù)據(jù)讀取完畢");
}
}
server端完成之后,接下來看客戶端client,client代碼和server端有點類似
package com.netty.test;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
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 Client {
public static void main(String[] args) throws Exception {
//server端不需要接收連接所有只用一個work來處理連接就可以。
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
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new ClientHandler());
}
});
//連接
ChannelFuture f = b.connect("127.0.0.1", 8888).sync();
f.channel().writeAndFlush(Unpooled.copiedBuffer("hello word".getBytes()));
// Wait until the connection is closed.
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
}
}
}
client的handler處理攔截數(shù)據(jù),用來接收服務(wù)端返回的響應(yīng)
package com.netty.test;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
public class ClientHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
}
/**
* 通道數(shù)據(jù)讀取
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf in = (ByteBuf) msg;
byte [] by = new byte [in.readableBytes()];
in.readBytes(by);
String body=new String(by,"utf-8");
System.out.println("接收服務(wù)器端返回信息:"+body);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
System.out.println("接收返回信息完成");
}
}
netty的helloworld就OK了,超級簡單吧。