Netty入门代码

Netty入门代码

public void start(int port) throws Exception {
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap b = new ServerBootstrap();
            b.channel(NioServerSocketChannel.class);
            b.option(ChannelOption.SO_BACKLOG, 2048);//初始化服务端可连接队 
            
			b.group(bossGroup, workerGroup)
					.childHandler(new ChannelInitializer<SocketChannel>() {
						@Override
						public void initChannel(SocketChannel ch)
								throws Exception {
							// server端接收到的是httpRequest,所以要使用HttpRequestDecoder进行解码
							ch.pipeline().addLast(new HttpRequestDecoder());
							// server端发送的是httpResponse,所以要使用HttpResponseEncoder进行编码
							ch.pipeline().addLast(new HttpResponseEncoder());
							ch.pipeline().addLast(new HttpServerHandlerReq());
							// 解决沾包拆包问题
							ch.pipeline().addLast(new LineBasedFrameDecoder(2048));
                           ch.pipeline().addLast(new StringDecoder());
							
						}
					}).option(ChannelOption.SO_BACKLOG, 4096)//1
					.option(ChannelOption.WRITE_SPIN_COUNT, 2048)
					.option(ChannelOption.SO_KEEPALIVE, true);//用于可能长时间没有数据交流的连接,如果在两小时内没有数据的通信时,TCP会自动发送一个活动探测数据报

			ChannelFuture f = b.bind(port);
			f.channel().closeFuture().sync();
		} finally {
			workerGroup.shutdownGracefully();
			bossGroup.shutdownGracefully();
		}
	}

程序主入口

public static void main(String[] args) throws Exception {
		TimeCache.start();
		HttpServerReq server = new HttpServerReq();
		int port = 6030;
		if (args.length > 0) {
			try {
				port = Integer.parseInt(args[0]);
			} catch (NumberFormatException e) {
				e.printStackTrace(); // TODO: handle error
			}
		}
		System.out.println("requestServer启动,端口:"+port);
		server.start(port);
	}

eclipse中 run as 即可启动netty

你可能感兴趣的:(Netty,netty,java)