我正在尝试开发其他API客户服务器。我的客户使用Java和Netty,服务器使用golang。当前,我遇到了一个非常奇怪的问题,我的客户端在某些情况下不将POST请求数据发送到服务器。
这里是详细信息:
-我的客户代码的一部分:
Bootstrap
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!");
}
});
-我从调试中获得的一些信息
这里的任何人之前都遇到过相同的问题,或者是否有解决此问题的想法。任何帮助将不胜感激。
我有一个问题,当使用异步方式时,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] to.spiritworker.proxy.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()
并打印原因,它将显示相同的错误。
我希望如果您检查自己的未来,也许您也可以找到原因。