IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> Netty创建server和client -> 正文阅读

[网络协议]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();
	}
}
  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2022-02-19 01:33:50  更:2022-02-19 01:35:53 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年10日历 -2024/10/5 11:18:30-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码