我正在编写一个小型Java程序,它使用Netty连接到unix域套接字以检索一些信息。我正在使用Netty 4.0.32.Final
并使用本机epoll包。这是我写的引导代码:
final Bootstrap bootstrap = new Bootstrap();
bootstrap
.group(new EpollEventLoopGroup())
.channel(EpollDomainSocketChannel.class)
.handler(
new ChannelInitializer<DomainSocketChannel>() {
@Override
protected void initChannel(
final DomainSocketChannel channel) throws Exception {
channel.pipeline().addLast(
new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(
final ChannelHandlerContext ctx,
final Object msg) throws Exception {
final ByteBuf buff = (ByteBuf) msg;
try {
buff.readBytes(
DomainSocket.this.out,
buff.readableBytes()
);
} finally {
buff.release();
}
}
@Override
public void exceptionCaught(
final ChannelHandlerContext ctx,
final Throwable cause) throws Exception {
Logger.error(
"Error occur when reading from Unix domain socket: %s",
cause.getMessage()
);
ctx.close();
}
}
);
}
}
);
对我来说这很好,但是当我跑步时
bootstrap.connect(new DomainSocketAddress("/tmp/test.sock"));
总是抱怨以下错误:
java.net.ConnectException: connect() failed: Connection refused: /tmp/test.sock
at io.netty.channel.epoll.Native.newConnectException(Native.java:504)
at io.netty.channel.epoll.Native.connect(Native.java:481)
at io.netty.channel.epoll.AbstractEpollStreamChannel.doConnect(AbstractEpollStreamChannel.java:567)
at io.netty.channel.epoll.EpollDomainSocketChannel.doConnect(EpollDomainSocketChannel.java:81)
at io.netty.channel.epoll.AbstractEpollStreamChannel$EpollStreamUnsafe.connect(AbstractEpollStreamChannel.java:627)
at io.netty.channel.DefaultChannelPipeline$HeadContext.connect(DefaultChannelPipeline.java:1097)
我可以知道引导程序设置有什么问题吗?感谢。
更新 我写了一个简单的服务器来测试单元测试中的代码。以下是服务器代码:
final ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap
.group(new EpollEventLoopGroup(), new EpollEventLoopGroup())
.channel(EpollServerDomainSocketChannel.class)
.childHandler(
new ChannelInitializer<ServerDomainSocketChannel>() {
@Override
protected void initChannel(
final ServerDomainSocketChannel channel)
throws Exception {
channel.pipeline().addLast(
new ChannelInboundHandlerAdapter() {
@Override
public void channelActive(
final ChannelHandlerContext ctx)
throws Exception {
final ByteBuf buff = ctx.alloc().buffer();
buff.writeBytes("This is a test".getBytes());
ctx.writeAndFlush(buff)
.addListener(
ChannelFutureListener.CLOSE
);
}
}
);
}
}
);
final ChannelFuture future =
bootstrap.bind(new DomainSocketAddress(input)).sync();
future.channel().closeFuture().sync();
我使用ExecutorService
在一个单独的线程中启动了此服务器代码。感谢。
答案 0 :(得分:1)
看起来没有什么东西在监听那个套接字。你在那里听任何服务器吗?你能查一下:
netstat -na | grep /tmp/test.sock