1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty5.example.file;
17
18 import io.netty5.bootstrap.ServerBootstrap;
19 import io.netty5.channel.Channel;
20 import io.netty5.channel.ChannelInitializer;
21 import io.netty5.channel.ChannelOption;
22 import io.netty5.channel.ChannelPipeline;
23 import io.netty5.channel.EventLoopGroup;
24 import io.netty5.channel.MultithreadEventLoopGroup;
25 import io.netty5.channel.nio.NioHandler;
26 import io.netty5.channel.socket.SocketChannel;
27 import io.netty5.channel.socket.nio.NioServerSocketChannel;
28 import io.netty5.handler.codec.LineBasedFrameDecoder;
29 import io.netty5.handler.codec.string.StringDecoder;
30 import io.netty5.handler.codec.string.StringEncoder;
31 import io.netty5.handler.logging.LogLevel;
32 import io.netty5.handler.logging.LoggingHandler;
33 import io.netty5.handler.ssl.SslContext;
34 import io.netty5.handler.ssl.SslContextBuilder;
35 import io.netty5.handler.ssl.util.SelfSignedCertificate;
36 import io.netty5.handler.stream.ChunkedWriteHandler;
37 import io.netty5.util.CharsetUtil;
38
39
40
41
42 public final class FileServer {
43
44 static final boolean SSL = System.getProperty("ssl") != null;
45
46 static final int PORT = Integer.parseInt(System.getProperty("port", SSL? "8992" : "8023"));
47
48 public static void main(String[] args) throws Exception {
49
50 final SslContext sslCtx;
51 if (SSL) {
52 SelfSignedCertificate ssc = new SelfSignedCertificate();
53 sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
54 } else {
55 sslCtx = null;
56 }
57
58
59 EventLoopGroup bossGroup = new MultithreadEventLoopGroup(1, NioHandler.newFactory());
60 EventLoopGroup workerGroup = new MultithreadEventLoopGroup(NioHandler.newFactory());
61 try {
62 ServerBootstrap b = new ServerBootstrap();
63 b.group(bossGroup, workerGroup)
64 .channel(NioServerSocketChannel.class)
65 .option(ChannelOption.SO_BACKLOG, 100)
66 .handler(new LoggingHandler(LogLevel.INFO))
67 .childHandler(new ChannelInitializer<SocketChannel>() {
68 @Override
69 public void initChannel(SocketChannel ch) throws Exception {
70 ChannelPipeline p = ch.pipeline();
71 if (sslCtx != null) {
72 p.addLast(sslCtx.newHandler(ch.bufferAllocator()));
73 }
74 p.addLast(
75 new StringEncoder(CharsetUtil.UTF_8),
76 new LineBasedFrameDecoder(8192),
77 new StringDecoder(CharsetUtil.UTF_8),
78 new ChunkedWriteHandler(),
79 new FileServerHandler());
80 }
81 });
82
83
84 Channel channel = b.bind(PORT).asStage().get();
85
86
87 channel.closeFuture().asStage().sync();
88 } finally {
89
90 bossGroup.shutdownGracefully();
91 workerGroup.shutdownGracefully();
92 }
93 }
94 }