Skip to content

Commit 0c11ff5

Browse files
committed
practice before lesson
1 parent 7fc6668 commit 0c11ff5

40 files changed

Lines changed: 472 additions & 124 deletions

02nio/nio01/src/main/java/java0/nio01/HttpServer01.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ private static void service(Socket socket) {
2424
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
2525
printWriter.println("HTTP/1.1 200 OK");
2626
printWriter.println("Content-Type:text/html;charset=utf-8");
27-
String body = "hello,nio";
27+
String body = "hello,nio1";
2828
printWriter.println("Content-Length:" + body.getBytes().length);
2929
printWriter.println();
3030
printWriter.write(body);

02nio/nio01/src/main/java/java0/nio01/HttpServer02.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ private static void service(Socket socket) {
2626
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
2727
printWriter.println("HTTP/1.1 200 OK");
2828
printWriter.println("Content-Type:text/html;charset=utf-8");
29-
String body = "hello,nio";
29+
String body = "hello,nio2";
3030
printWriter.println("Content-Length:" + body.getBytes().length);
3131
printWriter.println();
3232
printWriter.write(body);

02nio/nio01/src/main/java/java0/nio01/HttpServer03.java

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package java0.nio01;
22

33
import java.io.IOException;
4+
import java.io.InputStream;
45
import java.io.PrintWriter;
56
import java.net.ServerSocket;
67
import java.net.Socket;
@@ -27,7 +28,7 @@ private static void service(Socket socket) {
2728
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
2829
printWriter.println("HTTP/1.1 200 OK");
2930
printWriter.println("Content-Type:text/html;charset=utf-8");
30-
String body = "hello,nio";
31+
String body = "hello,nio3";
3132
printWriter.println("Content-Length:" + body.getBytes().length);
3233
printWriter.println();
3334
printWriter.write(body);
@@ -37,4 +38,15 @@ private static void service(Socket socket) {
3738
e.printStackTrace();
3839
}
3940
}
41+
42+
private static void handleInputStreanm(Socket socket) throws IOException {
43+
InputStream inputStream = socket.getInputStream();
44+
byte[] buffer = new byte[4096];
45+
StringBuilder sb = new StringBuilder();
46+
int tmp = 0;
47+
while ((tmp = inputStream.read(buffer))!=-1){
48+
sb.append(new String(buffer,"UTF-8"));
49+
}
50+
//
51+
}
4052
}

02nio/nio02/pom.xml

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,18 @@
2626

2727
<dependencies>
2828

29+
<dependency>
30+
<groupId>org.jetbrains.kotlin</groupId>
31+
<artifactId>kotlin-stdlib</artifactId>
32+
<version>1.3.70</version>
33+
</dependency>
34+
35+
<dependency>
36+
<groupId>com.squareup.okhttp3</groupId>
37+
<artifactId>okhttp</artifactId>
38+
<version>4.9.0</version>
39+
</dependency>
40+
2941
<dependency>
3042
<groupId>io.netty</groupId>
3143
<artifactId>netty-all</artifactId>

02nio/nio02/src/main/java/io/github/kimmking/gateway/NettyServerApplication.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ public class NettyServerApplication {
99
public final static String GATEWAY_VERSION = "1.0.0";
1010

1111
public static void main(String[] args) {
12-
String proxyServer = System.getProperty("proxyServer","http://localhost:8088");
12+
String proxyServer = System.getProperty("proxyServer","http://localhost:8801,http://localhost:8802,http://localhost:8803");
1313
String proxyPort = System.getProperty("proxyPort","8888");
1414

1515
// http://localhost:8888/api/hello ==> gateway API

02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/HttpRequestFilter.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,6 @@
55

66
public interface HttpRequestFilter {
77

8-
void filter(FullHttpRequest fullRequest, ChannelHandlerContext ctx);
8+
void filter(FullHttpRequest fullRequest);
99

1010
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package io.github.kimmking.gateway.filter;
2+
3+
4+
import io.netty.channel.ChannelHandlerContext;
5+
import io.netty.handler.codec.http.FullHttpRequest;
6+
import io.netty.handler.codec.http.HttpHeaders;
7+
8+
public class ReqHeadFilter implements HttpRequestFilter{
9+
10+
@Override
11+
public void filter(FullHttpRequest fullRequest) {
12+
HttpHeaders headers = fullRequest.headers();
13+
headers.set("nio","wp");
14+
}
15+
}

02nio/nio02/src/main/java/io/github/kimmking/gateway/inbound/HttpInboundHandler.java

Lines changed: 39 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,48 @@
11
package io.github.kimmking.gateway.inbound;
22

3+
import io.github.kimmking.gateway.filter.HttpRequestFilter;
4+
import io.github.kimmking.gateway.filter.ReqHeadFilter;
35
import io.github.kimmking.gateway.outbound.httpclient4.HttpOutboundHandler;
6+
import io.github.kimmking.gateway.outbound.netty4.NettyHttpClient;
7+
import io.github.kimmking.gateway.outbound.okhttp.OkhttpOutboundHandler;
8+
import io.github.kimmking.gateway.router.RandowRouter;
9+
import io.netty.buffer.Unpooled;
10+
import io.netty.channel.ChannelFutureListener;
411
import io.netty.channel.ChannelHandlerContext;
512
import io.netty.channel.ChannelInboundHandlerAdapter;
13+
import io.netty.handler.codec.http.DefaultFullHttpResponse;
614
import io.netty.handler.codec.http.FullHttpRequest;
15+
import io.netty.handler.codec.http.FullHttpResponse;
16+
import io.netty.handler.codec.http.HttpUtil;
717
import io.netty.util.ReferenceCountUtil;
18+
import okhttp3.OkHttpClient;
819
import org.slf4j.Logger;
920
import org.slf4j.LoggerFactory;
1021

22+
import java.util.Arrays;
23+
import java.util.Random;
24+
25+
import static io.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT;
26+
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
27+
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
28+
1129
public class HttpInboundHandler extends ChannelInboundHandlerAdapter {
1230

1331
private static Logger logger = LoggerFactory.getLogger(HttpInboundHandler.class);
1432
private final String proxyServer;
15-
private HttpOutboundHandler handler;
16-
33+
// private OkhttpOutboundHandler handler;
34+
private NettyHttpClient handler;
35+
private HttpRequestFilter filter;
36+
private RandowRouter randowRouter;
37+
1738
public HttpInboundHandler(String proxyServer) {
1839
this.proxyServer = proxyServer;
19-
handler = new HttpOutboundHandler(this.proxyServer);
40+
randowRouter = new RandowRouter();
41+
String route = randowRouter.route(Arrays.asList(proxyServer.split(",")));
42+
// handler = new OkhttpOutboundHandler(route);
43+
handler = new NettyHttpClient(route);
44+
filter = new ReqHeadFilter();
45+
2046
}
2147

2248
@Override
@@ -27,16 +53,16 @@ public void channelReadComplete(ChannelHandlerContext ctx) {
2753
@Override
2854
public void channelRead(ChannelHandlerContext ctx, Object msg) {
2955
try {
30-
//logger.info("channelRead流量接口请求开始,时间为{}", startTime);
31-
FullHttpRequest fullRequest = (FullHttpRequest) msg;
32-
// String uri = fullRequest.uri();
33-
// //logger.info("接收到的请求url为{}", uri);
34-
// if (uri.contains("/test")) {
35-
// handlerTest(fullRequest, ctx);
36-
// }
37-
38-
handler.handle(fullRequest, ctx);
39-
56+
if (msg instanceof FullHttpRequest){
57+
FullHttpRequest fullRequest = (FullHttpRequest) msg;
58+
if (fullRequest.uri().contains("/favicon.ico")){
59+
return;
60+
}
61+
filter.filter(fullRequest);
62+
63+
handler.handle(fullRequest, ctx);
64+
65+
}
4066
} catch(Exception e) {
4167
e.printStackTrace();
4268
} finally {

02nio/nio02/src/main/java/io/github/kimmking/gateway/inbound/HttpInboundServer.java

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,16 +13,18 @@
1313
import org.slf4j.Logger;
1414
import org.slf4j.LoggerFactory;
1515

16+
import java.io.File;
17+
1618

1719
public class HttpInboundServer {
1820
private static Logger logger = LoggerFactory.getLogger(HttpInboundServer.class);
1921

2022
private int port;
21-
23+
2224
private String proxyServer;
2325

2426
public HttpInboundServer(int port, String proxyServer) {
25-
this.port=port;
27+
this.port = port;
2628
this.proxyServer = proxyServer;
2729
}
2830

Lines changed: 58 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,62 @@
1-
//package io.github.kimmking.gateway.outbound;
2-
//
3-
//import io.netty.bootstrap.Bootstrap;
4-
//import io.netty.channel.ChannelFuture;
5-
//import io.netty.channel.ChannelInitializer;
6-
//import io.netty.channel.ChannelOption;
7-
//import io.netty.channel.EventLoopGroup;
8-
//import io.netty.channel.nio.NioEventLoopGroup;
9-
//import io.netty.channel.socket.SocketChannel;
10-
//import io.netty.channel.socket.nio.NioSocketChannel;
11-
//import io.netty.handler.codec.http.HttpRequestEncoder;
12-
//import io.netty.handler.codec.http.HttpResponseDecoder;
13-
//
14-
//public class NettyHttpClient {
15-
// public void connect(String host, int port) throws Exception {
16-
// EventLoopGroup workerGroup = new NioEventLoopGroup();
17-
//
1+
package io.github.kimmking.gateway.outbound.netty4;
2+
3+
import io.netty.bootstrap.Bootstrap;
4+
import io.netty.channel.*;
5+
import io.netty.channel.nio.NioEventLoopGroup;
6+
import io.netty.channel.socket.SocketChannel;
7+
import io.netty.channel.socket.nio.NioSocketChannel;
8+
import io.netty.handler.codec.http.*;
9+
import io.netty.handler.logging.LogLevel;
10+
import io.netty.handler.logging.LoggingHandler;
11+
12+
import java.util.Map;
13+
14+
public class NettyHttpClient {
15+
16+
Bootstrap b = new Bootstrap();
17+
EventLoopGroup workerGroup = new NioEventLoopGroup();
18+
19+
private String host;
20+
private int port;
21+
public NettyHttpClient(String backendUrl){
22+
backendUrl = backendUrl.endsWith("/")?backendUrl.substring(0,backendUrl.length()-1):backendUrl;
23+
String[] split = backendUrl.substring(backendUrl.indexOf("://") + 3).split(":");
24+
host = split[0];
25+
port = Integer.parseInt(split[1]);
26+
// connect(host,port);
27+
b.group(workerGroup);
28+
b.channel(NioSocketChannel.class);
29+
b.option(ChannelOption.SO_KEEPALIVE, true);
30+
}
31+
32+
public void connect(String host, int port,final FullHttpRequest fullRequest, final ChannelHandlerContext ctx) throws InterruptedException {
33+
1834
// try {
19-
// Bootstrap b = new Bootstrap();
20-
// b.group(workerGroup);
21-
// b.channel(NioSocketChannel.class);
22-
// b.option(ChannelOption.SO_KEEPALIVE, true);
23-
// b.handler(new ChannelInitializer<SocketChannel>() {
24-
// @Override
25-
// public void initChannel(SocketChannel ch) throws Exception {
26-
// // 客户端接收到的是httpResponse响应,所以要使用HttpResponseDecoder进行解码
27-
// ch.pipeline().addLast(new HttpResponseDecoder());
28-
// 客户端发送的是httprequest,所以要使用HttpRequestEncoder进行编码
29-
// ch.pipeline().addLast(new HttpRequestEncoder());
30-
// ch.pipeline().addLast(new HttpClientOutboundHandler());
31-
// }
32-
// });
33-
//
34-
// // Start the client.
35-
// ChannelFuture f = b.connect(host, port).sync();
36-
//
37-
//
38-
// f.channel().write(request);
39-
// f.channel().flush();
40-
// f.channel().closeFuture().sync();
35+
36+
b.handler(new ChannelInitializer<SocketChannel>() {
37+
@Override
38+
public void initChannel(SocketChannel ch) throws Exception {
39+
// 客户端接收到的是httpResponse响应,所以要使用HttpResponseDecoder进行解码
40+
//客户端发送的是httprequest,所以要使用HttpRequestEncoder进行编码
41+
ch.pipeline().addLast(new HttpResponseDecoder());
42+
ch.pipeline().addLast(new HttpRequestEncoder());
43+
ch.pipeline().addLast(new NettyHttpClientOutboundHandler(ctx.channel()));
44+
ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));
45+
}
46+
});
47+
// Start the client.
48+
Channel channel = b.connect(host, port).sync().channel();
49+
channel.writeAndFlush(fullRequest);
4150
// } finally {
4251
// workerGroup.shutdownGracefully();
43-
// }
4452
//
45-
// }
46-
//
47-
// public static void main(String[] args) throws Exception {
48-
// NettyHttpClient client = new NettyHttpClient();
49-
// client.connect("127.0.0.1", 8844);
50-
// }
51-
//}
53+
// }
54+
55+
}
56+
57+
public void handle(final FullHttpRequest fullRequest, final ChannelHandlerContext ctx) throws Exception {
58+
System.out.println(fullRequest.headers().get("nio"));
59+
60+
connect(host,port,fullRequest,ctx);
61+
}
62+
}

0 commit comments

Comments
 (0)