在SpringBoot中调用Netty实现的客户端出现连接问题?

新手上路,请多包涵

一个SpringBoot工程在被访问某个地址时会调用一个用Netty实现的客户端程序,客户端会和同样用Netty实现的服务端通信并得到结果,然后将结果用Json格式返回,这是整体流程。
现在我在本地运行时在SpringBoot这边遇到了这样的报错:
java.net.ConnectException: Connection refused: no further information: /127.0.0.1:8080
但是运行现象一切正常,网页有结果返回,服务端也正常运行。我想知道这个问题出在哪里,有没有大的影响,可以怎么解决?谢谢各位。
服务端部分代码:

public void bind(int port) throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .childHandler(new ChildChannelHandler());

        ChannelFuture f = b.bind(port).sync();

        f.channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel arg0) throws Exception {
        arg0.pipeline().addLast(new LineBasedFrameDecoder(1024));
        arg0.pipeline().addLast(new StringDecoder());
        arg0.pipeline().addLast(new TimeServerHandler());
    }
}

客户端部分代码:

public Response connect(int port, String host) throws Exception{
    EventLoopGroup group = new NioEventLoopGroup();
    try{
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception{
                        ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
                        ch.pipeline().addLast(new ResponseDecoder(Response.class));
                        ch.pipeline().addLast(TimeClient.this);
                    }
                });

        ChannelFuture f = b.connect(host, port).sync();

        f.channel().closeFuture().sync();
        return response;
    }finally {
        group.shutdownGracefully();
    }
}

@Override
@SuppressWarnings("unchecked")
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception{
    this.response = (Response) msg;
    ctx.channel().close();
}
阅读 4.5k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题