繁体   English   中英

java.net.ConnectException:调用SocketChannel.open时连接被拒绝

[英]java.net.ConnectException: Connection refused when SocketChannel.open is invoked

我正在尝试编写一个简单的程序来打开到本地地址的套接字通道。 每当我运行此程序时,我都会收到连接被拒绝的异常

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;

public class testSocket {

        public static void main(String [] args) {
                try {
                        InetAddress addr = InetAddress.getByName("localhost");
                        InetSocketAddress remoteAddress = new InetSocketAddress(addr, 19015);

                        // Open a new Socket channel and set it to non-blocking
                        SocketChannel socketChannel = SocketChannel.open();
                        socketChannel.configureBlocking(false);

                        // Issue the Connect call on the remote address.
                        socketChannel.connect(remoteAddress);
                } catch (Exception e) {
                        e.printStackTrace();
                }
        }
}

我得到的例外是

java.net.ConnectException: Connection refused
        at sun.nio.ch.Net.connect(Native Method)
        at sun.nio.ch.SocketChannelImpl.connect(SocketChannelImpl.java:464)
        at testSocket.main(testSocket.java:17)

我在Sun Solaris和HP-UX上遇到此问题。 在Linux机器上似乎工作正常。 谁能让我知道为什么拒绝连接? 我做了一个netstat -a并确认该端口没有被使用。

提前致谢!

当没有进程监听指定端口时,将收到“拒绝连接”消息(19015)。 您似乎正在尝试连接到不存在的服务。 netstat甚至告诉您该端口未使用!

从Javadoc中获取SocketChannel.connect()

如果此通道处于非阻塞模式,则此方法的调用将启动非阻塞连接操作。 如果像本地连接那样立即建立连接,则此方法返回true。 否则,此方法返回false,并且稍后必须通过调用finishConnect方法来完成连接操作。

当我在Linux上运行您的代码时,connect()返回false,因此也不例外。 如果添加对socketChannel.finishConnect()的调用,您将看到与在Solaris / HP-UX上相同的拒绝连接异常。

我怀疑在Solaris / HP-UX上connect()返回true,因此立即引发异常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM