簡體   English   中英

netty客戶端只能從服務器收到一個響應

[英]netty client can only receive one reponse from server

最近,我用netty 4編寫了一個客戶端和服務器,客戶端向服務器發送了5條消息,但是客戶端只能從服務器收到一個響應,這是我的代碼。

DTO:RpcRequest

package com.huawei.simple.rpc.base.request.dto;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;

import java.lang.reflect.Parameter;

@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class RpcRequest {
    private String requestId;
    private String interfaceName;
    private String methodName;
}

DTO:RpcResponse

package com.huawei.simple.rpc.base.response.dto;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class RpcResponse {
    private String requestId;
    private String responseMessage;
    private int responseCode;
    private Object responseBody;
}

編解碼器

public class ResponseDecoder extends ByteToMessageDecoder {
    private static ObjectMapper mapper = new ObjectMapper();
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        if (byteBuf.readableBytes() < 4) {
            return;
        }
        byteBuf.markReaderIndex();
        int dataLength = byteBuf.readInt();
        if (byteBuf.readableBytes() < dataLength) {
            byteBuf.resetReaderIndex();
            return;
        }
        byte[] data = new byte[dataLength];
        byteBuf.readBytes(data);
        RpcResponse response = mapper.readValue(data, RpcResponse.class);
        list.add(response);
    }
}
public class ResponseEncoder extends MessageToByteEncoder<RpcResponse> {
    private static ObjectMapper mapper = new ObjectMapper();
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, RpcResponse rpcResponse, ByteBuf byteBuf) throws Exception {
        byte[] bytes = mapper.writeValueAsBytes(rpcResponse);
        int dataLength = bytes.length;
        byteBuf.writeInt(dataLength);
        byteBuf.writeBytes(bytes);
        byteBuf.writeBytes(SerializationUtil.serialize(rpcResponse));

    }
}
public class RequestDecoder extends ByteToMessageDecoder {
    private static ObjectMapper mapper = new ObjectMapper();

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        if (byteBuf.readableBytes() < 4) {
            return;
        }
        byteBuf.markReaderIndex();
        int dataLength = byteBuf.readInt();
        if (byteBuf.readableBytes() < dataLength) {
            byteBuf.resetReaderIndex();
            return;
        }
        byte[] data = new byte[dataLength];
        byteBuf.readBytes(data);
        RpcRequest request = mapper.readValue(data, RpcRequest.class);
        list.add(request);
    }
}
public class RequestEncoder extends MessageToByteEncoder<RpcRequest> {
    private static ObjectMapper mapper = new ObjectMapper();
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, RpcRequest rpcRequest, ByteBuf byteBuf) throws Exception {
        byte[] bytes = mapper.writeValueAsBytes(rpcRequest);
        int dataLength = bytes.length;
        byteBuf.writeInt(dataLength);
        byteBuf.writeBytes(bytes);
    }
}

客戶

public class RpcClient {
    public static void main(String[] args) throws Exception {
        RpcClient server = new RpcClient();
        server.build();
    }

    public void build() {
        NioEventLoopGroup boss = new NioEventLoopGroup();
        Bootstrap s = new Bootstrap();
        s.group(boss).channel(NioSocketChannel.class)
            .option(ChannelOption.TCP_NODELAY,true)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline().addLast(new RequestEncoder());
                    socketChannel.pipeline().addLast(new ResponseDecoder());
                    socketChannel.pipeline().addLast(new RpcClientHandler());
                }
            });
        try {
            ChannelFuture future = s.connect(new InetSocketAddress("localhost",8080)).sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
        }
    }
}
public class RpcClientHandler extends ChannelInboundHandlerAdapter {
    private static AtomicInteger id = new AtomicInteger(1);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        for (int i = 0; i < 5; i++) {
            RpcRequest request = new RpcRequest();
            request.setRequestId(id.getAndIncrement() + "");
            request.setMethodName("helloWorld");
            request.setInterfaceName("interface");
            ChannelFuture future = ctx.writeAndFlush(request);
            future.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if (channelFuture.isSuccess()) {
                        System.out.println("Success");
                    }
                }
            });
            TimeUnit.SECONDS.sleep(5);
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        RpcResponse response = (RpcResponse) msg;
        System.out.println("get reponse from server " + response.toString());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}

服務器

public class RpcServer {
    public static void main(String[] args) throws Exception {
        RpcServer server = new RpcServer();
        server.build();
    }

    public void build() {
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        ServerBootstrap s = new ServerBootstrap();
        s.group(boss, worker).channel(NioServerSocketChannel.class)
            .option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.SO_BACKLOG, 10)
            .handler(new LoggingHandler(LogLevel.DEBUG))
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline().addLast(new RequestDecoder());
                    socketChannel.pipeline().addLast(new ResponseEncoder());
                    socketChannel.pipeline().addLast(new RpcServerHandler());
                }
            });
        try {
            ChannelFuture future = s.bind(new InetSocketAddress("localhost", 8080)).sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
}
public class RpcServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        RpcRequest request = (RpcRequest) msg;
        System.out.println("get request from client " + request.toString());
        RpcResponse response = new RpcResponse();
        response.setRequestId(request.getRequestId());
        ChannelFuture future = ctx.writeAndFlush(response);
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                if (channelFuture.isDone()) {
                    System.out.println("Done");
                } else if (channelFuture.isSuccess()) {
                    System.out.println("Success");
                }
            }
        });
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}

輸出為Server:

  1. 從客戶端RpcRequest獲取請求(requestId = 1,interfaceName = interface,methodName = helloWorld)完成
  2. 從客戶端獲取請求RpcRequest(requestId = 2,interfaceName = interface,methodName = helloWorld)完成
  3. 從客戶端獲取請求RpcRequest(requestId = 3,interfaceName = interface,methodName = helloWorld)完成
  4. 從客戶端RpcRequest獲取請求(requestId = 4,interfaceName = interface,methodName = helloWorld)完成
  5. 從客戶端RpcRequest獲取請求(requestId = 5,interfaceName = interface,methodName = helloWorld)完成

客戶

  1. 成功
  2. 成功
  3. 成功
  4. 成功
  5. 成功
  6. 從服務器RpcResponse獲取響應(requestId = 1,responseMessage = null,responseCode = 0,responseBody = null)

為什么我的客戶端僅從服務器收到一個響應?

您在ResponseEncoderResponseDecoder內部犯了一個錯誤(我猜第一個。

 public class ResponseDecoder extends ByteToMessageDecoder { private static ObjectMapper mapper = new ObjectMapper(); @Override protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception { if (byteBuf.readableBytes() < 4) { return; } byteBuf.markReaderIndex(); int dataLength = byteBuf.readInt(); if (byteBuf.readableBytes() < dataLength) { byteBuf.resetReaderIndex(); return; } byte[] data = new byte[dataLength]; byteBuf.readBytes(data); RpcResponse response = mapper.readValue(data, RpcResponse.class); list.add(response); } } public class ResponseEncoder extends MessageToByteEncoder<RpcResponse> { private static ObjectMapper mapper = new ObjectMapper(); @Override protected void encode(ChannelHandlerContext channelHandlerContext, RpcResponse rpcResponse, ByteBuf byteBuf) throws Exception { byte[] bytes = mapper.writeValueAsBytes(rpcResponse); int dataLength = bytes.length; byteBuf.writeInt(dataLength); byteBuf.writeBytes(bytes); byteBuf.writeBytes(SerializationUtil.serialize(rpcResponse)); } } 

您的編碼器將響應寫為:

int: length of bytes
bytes: The result of the mapper
serialize: the result of the serialize operation

但是這些在解碼器內部被讀取為:

int: length of bytes
bytes: The result of the mapper

您要么忘記處理解碼器中的多余字節,要么發送大量數據。

這導致程序的外觀無法讀取,因為客戶端實際上正在等待更多數據,因為我假設“序列化”的數據並非以零開頭,從而導致解碼器內部的長度異常高。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM