我正在尝试编写一个简单的程序来打开到本地地址的套接字通道。每当我运行此程序时,我都会收到连接被拒绝异常
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 并确认该端口未在使用中。
提前致谢!