开发者社区> 问答> 正文

关于netty传输到服务器之后如何解决:报错

我现在能够把文件的内容发送到服务器上了,可是不是预期的效果。我想把文件上传到服务器(是文件!!)而不是文件的内容。

以下是handler:

package netty_4;




import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;




import java.io.RandomAccessFile;
import java.util.Date;




public class TimeServerHandler extends ChannelInboundHandlerAdapter{
@Override
   public void channelRead(ChannelHandlerContext ctx, Object msg)
           throws Exception {
       System.out.println("服务器读取到客户端请求...");
       ByteBuf buf=(ByteBuf) msg;
       byte[] req=new byte[buf.readableBytes()];
       buf.readBytes(req);
       String body=new String(req);

//这部分可以无视掉
       RandomAccessFile randomFile = new RandomAccessFile("e://poem.txt", "rw");
       // 文件长度,字节数
       
       long fileLength = randomFile.length();
       // 将写文件指针移到文件尾。
       randomFile.seek(fileLength);
       randomFile.writeBytes(body);
       randomFile.close();

//到这里

//打印出的是文件的内容
       System.out.println(+body);
       String curentTime="QUERY TIME ORDER".equalsIgnoreCase(body)?new Date(System.currentTimeMillis()).toString():"BAD ORDER";
       ByteBuf resp=Unpooled.copiedBuffer(curentTime.getBytes());
       ctx.write(resp);
       System.out.println("服务器做出了响应");
   }
    
   @Override
   public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
       ctx.flush();
       System.out.println("服务器readComplete 响应完成");
       ctx.close();
   }
    
   @Override
   public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
           throws Exception {
       ctx.close();
       System.out.println("服务器异常退出"+cause.getMessage());
   }
}


展开
收起
kun坤 2020-06-07 15:58:18 597 0
1 条回答
写回答
取消 提交回答
  • 上传文件不就是上传内容吗?你在服务器端把内容写到和你上传文件同名的文件里,不就是上传完成了######不是说要用到FileRegion么

    2020-06-07 15:58:23
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
如何运维千台以上游戏云服务器 立即下载
网站/服务器取证 实践与挑战 立即下载
ECS计算与存储分离架构实践 立即下载