文件服务器实现一个可以展示指定用户输入的文件路径,返回对应文件内容的服务器 。

文章插图
实例代码服务端
public class FileServer { public static void main(String[] args) { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap serverBootstrap = new ServerBootstrap(); ChannelFuture channelFuture = serverBootstrap.group(bossGroup, workerGroup) .channel(NIOServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { // 编码 String ch.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8)) // 按照行进行解码 .addLast(new LineBasedFrameDecoder(1024)) // String 解码 .addLast(new StringDecoder(CharsetUtil.UTF_8)) // 大数据流的处理 .addLast(new ChunkedWriteHandler()) .addLast(new FileServerHandler()); } }) .bind(8889) .syncUninterruptibly(); channelFuture.channel().closeFuture().syncUninterruptibly(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } }}FileServerHandler.JAVA针对文件服务器的处理,实现如下:import java.io.RandomaccessFile;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.SimpleChannelInboundHandler;import io.netty.handler.stream.ChunkedFile;public class FileServerHandler extends SimpleChannelInboundHandler<String> { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { // 提醒客户端输入文件路径 ctx.writeAndFlush("HELLO: Type the path of the file to retrieve.n"); } @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { // 只读方式打开文件 try(RandomAccessFile file = new RandomAccessFile(msg, "r")) { long length = file.length(); ctx.write("OK: " + length + 'n'); ctx.write(new ChunkedFile(file)); ctx.writeAndFlush("n"); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); }}
推荐阅读
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- netty 服务端启动流程源码详解
- Netty 实战:如何实现 HTTP 服务器?
- 如何实现几百台SIP终端实现自动化部署
- 如何在 Linux 终端查看图像
- 龙井怎么分辨好坏,如何分辨真正的炭焙型铁观音
- 如何让肱二头肌变小呢
- 绿茶要怎么样保存,绿茶如何保存
- 白琳工夫怎么泡,如何区分白琳工夫
- 保存茶叶关键2,黄山毛峰如何保存
- 母亲的意义是什么如何教育世人
