1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package io.netty.example.file;
18
19 import io.netty.channel.ChannelFutureListener;
20 import io.netty.channel.ChannelHandlerContext;
21 import io.netty.channel.DefaultFileRegion;
22 import io.netty.channel.SimpleChannelInboundHandler;
23 import io.netty.handler.ssl.SslHandler;
24 import io.netty.handler.stream.ChunkedFile;
25
26 import java.io.RandomAccessFile;
27
28 public class FileServerHandler extends SimpleChannelInboundHandler<String> {
29
30 @Override
31 public void channelActive(ChannelHandlerContext ctx) {
32 ctx.writeAndFlush("HELLO: Type the path of the file to retrieve.\n");
33 }
34
35 @Override
36 public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
37 RandomAccessFile raf = null;
38 long length = -1;
39 try {
40 raf = new RandomAccessFile(msg, "r");
41 length = raf.length();
42 } catch (Exception e) {
43 ctx.writeAndFlush("ERR: " + e.getClass().getSimpleName() + ": " + e.getMessage() + '\n');
44 return;
45 } finally {
46 if (length < 0 && raf != null) {
47 raf.close();
48 }
49 }
50
51 ctx.write("OK: " + raf.length() + '\n');
52 if (ctx.pipeline().get(SslHandler.class) == null) {
53
54 ctx.write(new DefaultFileRegion(raf.getChannel(), 0, length));
55 } else {
56
57 ctx.write(new ChunkedFile(raf));
58 }
59 ctx.writeAndFlush("\n");
60 }
61
62 @Override
63 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
64 cause.printStackTrace();
65
66 if (ctx.channel().isActive()) {
67 ctx.writeAndFlush("ERR: " +
68 cause.getClass().getSimpleName() + ": " +
69 cause.getMessage() + '\n').addListener(ChannelFutureListener.CLOSE);
70 }
71 }
72 }
73