我是新来的。我有净值问题。超过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还是比较陌生的。谢谢。
答案 0 :(得分:1)
您将需要编写自己的解码器,该解码器将缓冲数据,直到您收到所有内容为止。通常,这是通过扩展import string
def ispangram(str1, alphabet=string.ascii_lowercase):
for char in set(alphabet):
if char not in str1:
return False
return True
来完成的,只有完成后才将ByteToMessageDecoder
放在ByteBuf
上。
类似的东西:
out