问题描述
我正在尝试编写一个简单的程序来打开到本地地址的套接字通道.每当我运行此程序时,我都会收到连接被拒绝的异常
I am trying to write a simple program to open a socket channel to a local address. I get a connection refused exception whenever I run this program
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并确认该端口未被使用.
I encounter this issue with Sun Solaris and HP - UX. It seems to work fine on a Linux machine. Can anyone let me know why the connection is being refused? I did a netstat -a and confirmed that the port is not in use.
提前谢谢!
推荐答案
从Javadoc中获取SocketChannel.connect()
From the Javadoc for SocketChannel.connect()
当我在Linux上运行您的代码时,connect()返回false,因此没有异常.如果添加对socketChannel.finishConnect()的调用,您将看到与在Solaris/HP-UX上相同的拒绝连接异常.
When I run your code on Linux, connect() returns false hence there is no exception. If you add a call to socketChannel.finishConnect() you will see the same connection refused exception as you get on Solaris/HP-UX.
我怀疑在Solaris/HP-UX上connect()返回true,因此会立即引发异常.
I suspect that on Solaris/HP-UX connect() returns true hence the exception is thrown immediately.
这篇关于java.net.ConnectException:调用SocketChannel.open时连接被拒绝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!