2015-06-22 69 views
1
得到完整的信息

我的代碼是這樣的服務器端的處理程序類網狀:如何從客戶端

package nettyechoserver; 

import io.netty.buffer.ByteBuf; 
import io.netty.channel.ChannelFuture; 
import io.netty.channel.ChannelFutureListener; 
import io.netty.channel.ChannelHandler.Sharable; 
import io.netty.channel.ChannelHandlerAdapter; 
import io.netty.channel.ChannelHandlerContext; 
import io.netty.util.ReferenceCountUtil; 

/** 
* Handler implementation for the echo server. 
*/ 

@Sharable 
public class EchoServerHandler extends ChannelHandlerAdapter { 
int i = 0; 
ByteBuf in = null; 
byte[] inByteBuf=new byte[78231]; 
@Override 
public void handlerAdded(ChannelHandlerContext ctx) { 
    in = ctx.alloc().buffer(4); // (1) 
} 
@Override 
public void channelRead(ChannelHandlerContext ctx, Object msg) { 
    in = (ByteBuf) msg; 
    try { 
     while (in.isReadable()) { // (1) 

      inByteBuf[i] = in.readByte(); 

      System.out.flush(); 
      i++; 
     } 
    } finally { 
     ReferenceCountUtil.release(msg); // (2) 
    } 
} 

@Override 
public void channelReadComplete(ChannelHandlerContext ctx) { 
    final ByteBuf time = ctx.alloc().buffer(4); 
    System.out.println("total read: " + i); 
    String s = "Message Received"; 
     time.writeBytes(s.getBytes()); 
     final ChannelFuture f = ctx.writeAndFlush(time); // (3) 
     f.addListener(new ChannelFutureListener() { 

      public void operationComplete(ChannelFuture future) { 
       assert f == future; 
       ctx.close(); 
      } 
     }); 
} 

@Override 
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 
    // Close the connection when an exception is raised. 
    cause.printStackTrace(); 
    ctx.close(); 
} 
} 

現在的問題是,我在字節形式和總的接收到的數據大小發送76個KB數據16 kb只有其他數據每次都會丟失 任何人都可以幫助我接收我的整個數據我正在等待您的答案

回答

1

這裏發生的是您收到第一個數據塊(TCP/IP方式,分成多個部分一個大框架),但你只處理第一個數據包,而不是以下數據(並且你應該在之後接收其他數據包)。

你應該使用一些符合你需要的解碼器,一個解碼器可以在信息包之後保留信息包,直到你得到所有需要的信息傳遞給下一個處理器,這將是你的業務。

例如,您可以使用LengthFieldBasedFrameDecoder或最簡單的FixedLengthFrameDecoder