我正在尝试开发一个REST API客户端服务器。我的客户端使用Java和Netty,服务器使用golang。 当前,我遇到了一个非常奇怪的问题,我的客户端在某些情况下不将POST请求数据发送到服务器。
以下是详细信息:
-我的客户代码的一部分:
引导程序
Bootstrap b = new Bootstrap()
.group(group)
.channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.option(ChannelOption.SO_KEEPALIVE, true)
.remoteAddress(Host, Port)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
ch.pipeline()
.addLast(new HttpClientCodec())
.addLast(new ClientHandler());
}
});
return b.connect().syncUninterruptibly().channel();
发送请求
if (channel.isActive() && channel.isWritable()) {
FullHttpRequest postRequest = new DefaultFullHttpRequest(
HttpVersion.HTTP_1_1,
HttpMethod.POST,
uri);
postRequest.headers().set(HttpHeaderNames.HOST, Host + ":" + Port);
postRequest.headers().set("Content-Type", "application/json; charset=UTF-8");
postRequest.headers().set(HttpHeaderNames.CONTENT_LENGTH, data.getBytes(StandardCharsets.UTF_8).length);
postRequest.content().writeBytes(data.getBytes(StandardCharsets.UTF_8));
ChannelFuture channelFuture = channel.writeAndFlush(postRequest);
channelFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
logger.info("Send completed!");
}
});
-我从调试中获得的一些信息
这里有没有人遇到过同样的问题,或者对如何解决这个问题有任何想法。 任何帮助将不胜感激。
答案 0 :(得分:0)
我有一个问题,当使用异步方式时,netty会吞下异常,甚至使用“发送完成!”来完成将来。但是我的Wireshark日志从未显示过超过SYN-> SYN,ACK-> ACK流。
我的代码如下:
ChannelFuture channelFuture = channel.writeAndFlush(new byte[10]);
channelFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
logger.info("Send completed!");
}
});
我将代码更改为像这样进行同步之后:
channel.writeAndFlush(new byte[10]).sync();
我终于发现实际上存在一个错误:
[11:58:50] [WARN] xx.xxxx.xxxxx.ProxyClient.operationComplete()引发了异常 java.lang.UnsupportedOperationException:不支持的消息类型:[B(预期:ByteBuf,FileRegion)
结果是我需要writeAndFlush(Unpooled.wrappedBuffer(new byte[10]))
包装数组。
所以我了解到异步方式会很高兴地告诉您它已成功!
但是等等,然后我发现它可能没有吞下任何异常,只是我没有检查它!
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if(!future.isSuccess()){
logger.info(future.cause());
}
}
因此,如果您更改以后的侦听器以检查isSuccess()
并打印原因,则会向您显示相同的错误。
我希望如果您检查自己的未来,也许您也可以找到原因。