Netty 小练习,并思考其中问题

主要思考,代码中的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 的显示。就会明白了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值