今天分享一下netty的helloworld,简单容易上手。
首先看server(注释已在代码中标明)
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();
//辅助类 用于帮助我们创建netty服务
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(boss, work)
.channel(NioServerSocketChannel.class)//设置NIO模式
.option(ChannelOption.SO_BACKLOG, 1024)//设置tcp缓冲区
.childOption(ChannelOption.SO_SNDBUF, 32*1024)//设置发送缓冲区数据大小
.option(ChannelOption.SO_RCVBUF, 32*1024)//设置接收缓冲区数据大小
.childOption(ChannelOption.SO_KEEPALIVE, true)//保持长连接
.childHandler(new ChannelInitializer() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//通道的初始化,数据传输过来进行拦截及执行
ch.pipeline().addLast(new ServerHandler());
}
});
ChannelFuture f = serverBootstrap.bind(8888).sync();//绑定端口启动服务
f.channel().closeFuture().sync();
work.shutdownGracefully();
boss.shutdownGracefully();
}
}
接下来在看数据拦截的handler,这个里边主要是进行数据的处理。
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("数据激活");
}
/**
* 通道数据读取
*/
@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("服务器收到数据:"+body);
String response="进行返回给客户端的响应"+body;
ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
System.out.println("数据读取完毕");
}
}
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() {
@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处理拦截数据,用来接收服务端返回的响应
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 {
}
/**
* 通道数据读取
*/
@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("接收服务器端返回信息:"+body);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
System.out.println("接收返回信息完成");
}
}
netty的helloworld就OK了,超级简单吧。