2009-07-02 58 views
1

我想寫一個簡單的程序來打開一個套接字通道到本地地址。我得到一個連接被拒絕異常,每當我運行這個程序java.net.ConnectException:當SocketChannel.open被調用時連接被拒絕

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並確認該端口未被使用。

在此先感謝!

回答

0

從()的Javadoc SocketChannel.connect

如果此信道是在非阻塞模式,則此方法的調用發起非阻塞連接操作。如果立即建立連接(就像本地連接可能發生的那樣),則此方法返回true。否則,此方法返回false,並且以後必須通過調用finishConnect方法完成連接操作。

當我在Linux上運行你的代碼時,connect()返回false,因此沒有例外。如果您將調用添加到socketChannel.finishConnect(),您將看到與Solaris/HP-UX上的相同的連接拒絕異常。

我懷疑在Solaris/HP-UX上connect()返回true,因此立即拋出異常。

1

「連接被拒絕」消息是您在指定端口上沒有進程偵聽時會收到的消息(19015年)。它看起來像你試圖連接到一個不存在的服務。 netstat甚至告訴你,該端口沒有被使用!

相關問題