我是新来的。我有净值问题。超过1024个字节时,数据将被截断。当我从标准io套接字移植到Netty时,使用io我可以读取x字节的任何数据,因此出现了此问题TheClient是一个单独的线程,用于处理已被接受的套接字连接]
公共类TheClient扩展线程{
private DataInputStream dis; private DataOutputStream dos; public TheClient(Socket s,SocketHandler sockHandler,SocketHandlerListener sockListener){ try{ //open the streams to read and write data dis= new DataInputStream(this.s.getInputStream()); dos=new DataOutputStream(this.s.getOutputStream()); //this is how i read the data of any x bytes in server int len = dis.readInt(); if(len >0){ byte[]buffer = new byte[len]; dis.readFully(buffer,0,buffer.length); String output = new String(buffer,0,buffer.length); CLIENT_REQUEST +=output; } //System.out.println("what i read: "+CLIENT_REQUEST); }catch(Exception ex){ ex.printStackTrace(); } } }
我如何使用netty读取相同的x字节而不丢失数据。我试过了
public class NettyServer{ public static void main(String []args){ EventLoopGroup group = new NioEventLoopGroup(); try{ ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(group); serverBootstrap.channel(NioServerSocketChannel.class);//"localhost", serverBootstrap.localAddress(new InetSocketAddress(Integer.valueOf(port))); serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() { protected void initChannel(SocketChannel socketChannel) throws Exception { ChannelPipeline pipeline = socketChannel.pipeline(); //pipeline.addLast(new HelloServerHandler2()); pipeline.addLast(new ClientHandler()); } }); ChannelFuture channelFuture = serverBootstrap.bind().sync(); channelFuture.channel().closeFuture().sync(); } catch(Exception e){ e.printStackTrace(); } finally { group.shutdownGracefully().sync(); } } } }
然后我有ClientHandler类,其中发生读取并且数据被截断了
public class ClientHandler extends ChannelInboundHandlerAdapter { public ClientHandler () { System.out.println("Preparing..."); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf inBuffer = (ByteBuf) msg; //supposed to read 100kb data or string String received = inBuffer.toString(CharsetUtil.UTF_8); //but output has been truncated to 1kb or less System.out.println("Server received: " + received); ctx.write(Unpooled.copiedBuffer("Hello : " + received, CharsetUtil.UTF_8)); System.out.println("done from server: " ); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.writeAndFlush(Unpooled.EMPTY_BUFFER) .addListener(ChannelFutureListener.CLOSE); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } }
我已经搜索了SO,但是没有一个对我有用。在附加到StringBuffer或somethng时,我如何真正地完整读取我的完整数据,直到完成...请帮助我。我正在学习Netty,对Java还是比较陌生的。谢谢。
我是新来的。我有净值问题。超过1024个字节时,数据将被截断。从标准io套接字移植到Netty时,使用io可以读取x字节的任何数据...
您将需要编写自己的解码器,该解码器将缓冲数据,直到您收到所有内容为止。通常,这是通过扩展ByteToMessageDecoder
并仅在完成后才将ByteBuf
放到out
来完成的。