版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
服务端
1 Server解析
public class TestServer {
public static void main(String[] args) throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup();//1
EventLoopGroup workerGroup = new NioEventLoopGroup();//2
try{
ServerBootstrap serverBootstrap = new ServerBootstrap();//3
serverBootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class)
.childHandler(new TestServerInitializer());//4
System.out.println("0");
ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();//5
channelFuture.channel().closeFuture().sync();
System.out.println("1");
}finally {
bossGroup.shutdownGracefully();//6
workerGroup.shutdownGracefully();
System.out.println("2");
}
}
}
1:boossGroup用于处理客户端的连接,其他事情都不做;workerGroup 真正用来工作,读取连接内容,写如内容等等。这两个的类是一样,本质上两者都是nio异步的处理的事件循环对象。
3.一个辅助netty启动的封装类,用于简化服务器的创建工作。
4.NioServerSocketChannel是对nio中的ServerSocketChannel的封装;TestServerInitializer是我们自己写的类。这里有明显的链式调用风格。
childHandler和handler的区别:handler是针对bossGroup,childHandler是针对workerGroup
5.ChannelFuture 是对Future接口的扩展实现。
6. 可以使线程优雅地关闭
2 childHandler参数解析
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;
public class TestServerInitializer extends ChannelInitializer<SocketChannel> {//1
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline channelPipeline = ch.pipeline();
channelPipeline.addLast("httpServerCodec",new HttpServerCodec());//2
channelPipeline.addLast("testHttpServerHandler",new TestHttpServerHandler());//2
}
}
- ChannelInitializer 通道初始化器。一个模板
- 使用netty提供的或自己编写的编解码器,addLast的第一个参数为编解码器的名称。可传可不传,不传有默认名。建议传。
3 自定义Handler
mport io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import java.net.URI;
/**
* @author zhuyc
* @create 2018-12-28 21:41
*/
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {//1
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
if(msg instanceof HttpRequest){
HttpRequest httpRequest = (HttpRequest)msg;
System.out.println("请求方法名:"+httpRequest.method().name());//GET
URI uri = new URI(httpRequest.uri());
System.out.println(uri.getPath());//path
ByteBuf content = Unpooled.copiedBuffer("hello world", CharsetUtil.UTF_8);
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,content);
response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
response.headers().set(HttpHeaderNames.CONTENT_LENGTH,content.readableBytes());
ctx.writeAndFlush(response);
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
System.out.println("handlerAdded");
Channel channel = ctx.channel();
channelGroup.writeAndFlush("[服务器] - " + channel.remoteAddress() +" 加入\n");
channelGroup.add(channel);
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
System.out.println("handlerRemoved");
Channel channel = ctx.channel();
//netty会自动将channel组中的断掉的channel删掉
//channelGroup.remove(channel);
channelGroup.writeAndFlush("[服务器] - " + channel.remoteAddress() +" 离开\n");
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("channelActive");
Channel channel = ctx.channel();
channelGroup.writeAndFlush( channel.remoteAddress() +" 上线\n");
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println("channelInactive");
Channel channel = ctx.channel();
channelGroup.writeAndFlush( channel.remoteAddress() +" 下线\n");
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
}
SimpleChannelInboundHandle
r也相当于一个模板类,这里是inbound也有对应的outbound。
二 客户端
1 启动类
略…
2 ChannelInitializer
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
/**
* @author zhuyc
* @create 2019-01-01 22:47
*/
public class MyClientInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4,0,4));
pipeline.addLast(new LengthFieldPrepender(4));
pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
pipeline.addLast(new MyClientHandler());
}
}
3 自定义处理器
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import java.time.LocalDateTime;
/**
* @author zhuyc
* @create 2019-01-01 22:48
*/
public class MyClientHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println(ctx.channel().remoteAddress());
System.out.println("client output: "+msg);
ctx.writeAndFlush("from client: "+ LocalDateTime.now());
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}