Netty创建server和client

NettyServer


public class NettyServer {

	public static void main(String[] args) {
		// 创建两个NioEventLoopGroup bossGroup监听客户端请求 workGroup处理每条连接的数据读写。
		NioEventLoopGroup bossGroup = new NioEventLoopGroup();
		NioEventLoopGroup workerGroup = new NioEventLoopGroup();
		ServerBootstrap serverBootstrap = new ServerBootstrap();
		serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
				.childHandler(new ChannelInitializer<SocketChannel>() {

					@Override
					protected void initChannel(SocketChannel ch) throws Exception {
						ChannelPipeline pipeline = ch.pipeline();
						// 处理http消息的编解码
						pipeline.addLast("httpServerCodec", new HttpServerCodec());
						pipeline.addLast("HttpRequestDecoder", new HttpRequestDecoder());
						pipeline.addLast("aggregator", new HttpObjectAggregator(65535));
						// 添加自定义的ChannelHandler
						pipeline.addLast("httpServerHandler", new SimpleChannelInboundHandler<FullHttpRequest>() {

							@Override
							protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg)
									throws Exception {
								ctx.channel().remoteAddress();
								FullHttpRequest request = msg;
								System.out.println("请求方法名称:" + request.method().name());
								System.out.println("uri:" + request.uri());
								ByteBuf buf = request.content();
								System.out.print(buf.toString(CharsetUtil.UTF_8));
								ByteBuf byteBuf = Unpooled.copiedBuffer("hello world", CharsetUtil.UTF_8);
								FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
										HttpResponseStatus.OK, byteBuf);
								response.headers().add(HttpHeaderNames.CONTENT_TYPE, "text/plain");
								response.headers().add(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());
								ctx.writeAndFlush(response);
							}
						});
					}
				});
		ChannelFuture future;
		try {
			future = serverBootstrap.bind(8080).sync();
			// 等待服务端口关闭
			future.channel().closeFuture().sync();
		} catch (InterruptedException e) {
		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
}

NettyHttpClient


public class NettyHttpClient {
	public static void main(String[] args) {
		String host = "127.0.0.1";
		int port = 8080;
		EventLoopGroup group = new NioEventLoopGroup();
		Bootstrap bootstrap = new Bootstrap();
		bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
			@Override
			protected void initChannel(SocketChannel ch) throws Exception {
				ChannelPipeline pipeline = ch.pipeline();
				pipeline.addLast(new HttpClientCodec());
				pipeline.addLast(new HttpObjectAggregator(65535));
				pipeline.addLast(new SimpleChannelInboundHandler<FullHttpResponse>() {

					@Override
					public void channelActive(ChannelHandlerContext ctx) throws Exception {
						URI uri = new URI("http://127.0.0.1:8080");
						String msg = "hello?";
						FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
								uri.toASCIIString(), Unpooled.wrappedBuffer(msg.getBytes("UTF-8")));

						request.headers().set(HttpHeaderNames.CONTENT_LENGTH, request.content().readableBytes());
						// 发送http请求
						ctx.channel().writeAndFlush(request);
					}

					// 处理服务端返回的消息
					@Override
					protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {
						FullHttpResponse response = msg;
						response.headers().get(HttpHeaderNames.CONTENT_TYPE);
						ByteBuf buf = response.content();
						System.out.println(buf.toString(io.netty.util.CharsetUtil.UTF_8));
					}
				});
			}
		});
		// 启动客户端.
		ChannelFuture future;
		try {
			future = bootstrap.connect(host, port).sync();
			future.channel().closeFuture().sync();
		} catch (InterruptedException e) {
		}
		group.shutdownGracefully();
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值