基于http的netty demo

1.引入netty的pom

<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>4.1.10.Final</version>
</dependency>

2.编写代码

 1 package com.bill.httpdemo;
 2 
 3 
 4 import io.netty.bootstrap.ServerBootstrap;
 5 import io.netty.channel.ChannelFuture;
 6 import io.netty.channel.EventLoopGroup;
 7 import io.netty.channel.nio.NioEventLoopGroup;
 8 import io.netty.channel.socket.nio.NioServerSocketChannel;
 9 
10 public class HttpServer {
11 
12     public static void main(String[] args) throws Exception {
13 
14         // 这2个group都是死循环,阻塞式
15         EventLoopGroup bossGroup = new NioEventLoopGroup();
16         EventLoopGroup workerGroup = new NioEventLoopGroup();
17 
18         try {
19             ServerBootstrap serverBootstrap = new ServerBootstrap();
20             serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).
21                     childHandler(new HttpServerInitializer());
22 
23             ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();
24             channelFuture.channel().closeFuture().sync();
25         } finally {
26             bossGroup.shutdownGracefully();
27             workerGroup.shutdownGracefully();
28         }
29     }
30 
31 }
32 
33 package com.bill.httpdemo;
34 
35 import io.netty.buffer.ByteBuf;
36 import io.netty.buffer.Unpooled;
37 import io.netty.channel.ChannelHandlerContext;
38 import io.netty.channel.SimpleChannelInboundHandler;
39 import io.netty.handler.codec.http.*;
40 import io.netty.util.CharsetUtil;
41 
42 import java.net.URI;
43 
44 public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
45 
46     /**
47      * 读取客户端请求,并且返回给客户端数据的方法
48      */
49     @Override
50     protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws Exception {
51 
52         if(!(httpObject instanceof HttpRequest)) {
53             return;
54         }
55 
56         System.out.println("excute channelRead0");
57 
58         HttpRequest httpRequest = (HttpRequest) httpObject;
59 
60         URI uri = new URI(httpRequest.uri());
61         System.out.println(uri.getPath());
62 
63         ByteBuf content = Unpooled.copiedBuffer("Hello World", CharsetUtil.UTF_8);
64         FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
65                 HttpResponseStatus.OK, content);
66         response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
67         response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
68 
69         channelHandlerContext.writeAndFlush(response);
70     }
71 }
72 
73 package com.bill.httpdemo;
74 
75 import io.netty.channel.ChannelInitializer;
76 import io.netty.channel.ChannelPipeline;
77 import io.netty.channel.socket.SocketChannel;
78 import io.netty.handler.codec.http.HttpServerCodec;
79 
80 public class HttpServerInitializer extends ChannelInitializer<SocketChannel> {
81 
82     @Override
83     protected void initChannel(SocketChannel socketChannel) throws Exception {
84 
85         ChannelPipeline pipeline = socketChannel.pipeline();
86 
87         pipeline.addLast("HttpServerCodec", new HttpServerCodec());
88         pipeline.addLast("HttpServerHandler", new HttpServerHandler());
89     }
90 }

 

3.启动服务器,执行HttpServer的main方法

4.浏览器输入网址:

http://127.0.0.1:8899/hello/world

客户端输出:

服务器输出:

 

完整代码下载:

https://download.csdn.net/download/mweibiao/10551574

转载于:https://www.cnblogs.com/billmiao/p/9872168.html

以下是一个简单的 Netty 服务器和客户端的示例代码: 服务端: ```java import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import io.netty.util.CharsetUtil; public class NettyServerDemo { private static final int PORT = 8080; public static void main(String[] args) { ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(new NioEventLoopGroup(), new NioEventLoopGroup()) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8)); pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8)); pipeline.addLast(new SimpleChannelInboundHandler<String>() { @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { System.out.println("Server received: " + msg); ctx.writeAndFlush("Hello from server!"); } }); } }); Channel channel = serverBootstrap.bind(PORT).syncUninterruptibly().channel(); System.out.println("Server started on port " + PORT); channel.closeFuture().addListener((ChannelFutureListener) future -> { System.out.println("Server stopped."); }); } } ``` 客户端: ```java import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import io.netty.util.CharsetUtil; import java.util.Scanner; public class NettyClientDemo { private static final String HOST = "localhost"; private static final int PORT = 8080; public static void main(String[] args) { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(new NioEventLoopGroup()) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8)); pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8)); pipeline.addLast(new SimpleChannelInboundHandler<String>() { @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { System.out.println("Client received: " + msg); } }); } }); Channel channel = bootstrap.connect(HOST, PORT).syncUninterruptibly().channel(); System.out.println("Client connected to server on " + HOST + ":" + PORT); Scanner scanner = new Scanner(System.in); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if ("exit".equals(line)) { break; } channel.writeAndFlush(line); } channel.close().addListener((ChannelFutureListener) future -> { System.out.println("Client disconnected from server."); }); } } ``` 这个示例代码实现了一个简单的文本协议,客户端输入的所有内容都会发送到服务端,服务端会将收到的消息原样返回给客户端。你可以基于这个示例代码构建更复杂的网络应用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值