主要思考,代码中的handler 是什么情况下新建对象。
package com.zhu.netty2;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.List;
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;
public class NettyServer {
private int port;
public NettyServer(int port) {
this.port = port;
}
private List<ResponseServerHandler> handlers = new ArrayList<>();
public void run() throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
System.out.println("准备运行端口: " + port);
ServerBootstrap b = new ServerBootstrap();
b = b.group(bossGroup, workerGroup);
b = b.channel(NioServerSocketChannel.class);
b = b.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ResponseServerHandler responseServerHandler = new ResponseServerHandler();
ch.pipeline().addLast(responseServerHandler);
handlers.add(responseServerHandler);
check(handlers); //思考 responseServerHandler 是不是同一个对象。什么情况下新建一个handler 对象
}
});
b = b.option(ChannelOption.SO_BACKLOG, 128);
b = b.childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture f = b.bind(port).sync();
f.channel().closeFuture().sync();
}
public void check(List<ResponseServerHandler> a) {
System.out.println(a.size());
if (a.size() > 2) {
if(a.get(0) == a.get(0)) {
System.out.println("同一个对象");
} else {
System.out.println("不是同一个对象");
}
}
}
public static void main(String[] args) throws InterruptedException {
int port;
if(args.length > 0) {
port = Integer.parseInt(args[0]);
} else {
port = 8000;
}
new NettyServer(port).run();
}
}
启动代码测试步骤:
1.通过cmd 使用telnet 测试
2.输入指令 telnet ip 端口
3.重复 第二步骤 查看eclipse 中 console 的显示。就会明白了。