當Socket的構造方法請求鏈接服務器的時候,可能會產生以下異常:
UnknownHostException:當無法識別主機的名字或者ip地址的時候,就會拋出這種異常,比如下面的程序不輸入參數直接運行,hostname自然不是可以識別的主機名稱,於是就會報出這個異常。
ConnectException:當沒有服務器進程監聽指定的端口,或者說服務器進程拒絕鏈接的時候,就會拋出這種異常。比如運行改程序,參數設置爲localhost 8888,那麼因爲主機沒有進程監聽8888,所以就會報出這個異常;還有一種情況是服務器進程拒絕鏈接。(這個情況請參看下一篇博客)
SocketTimeOutException:當等待鏈接超時,就會報出這個異常,比如將socket.connect(remoteAddr,10000)的第二個參數改爲1(ms)那麼無論再正確的服務器ip和端口,都會報出這個異常,異常產生的先後由catch的順序決定。
BindException:如果無法把Socket對象和指定的主機ip地址或者端口綁定就會報出這個異常。
socket的connect(SocketAddress remoteAddr,int timeout)是用來鏈接服務器的相關設置
還有個方法是bind(SocketAddress localAddr,int port)用來將Socket對象和本地的ip地址或者端口綁定
SocketAddress localAddr = new InetSocketAddress(host,port);
socket.bind(localAddr);如果本機ip地址不是這個,就會報出異常
import java.io.IOException;
import java.net.BindException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
public class ConnectTester {
public static void main(String args[]) {
String host = "hostname";
int port = 25;
if (args.length > 1) {
host = args[0];
port = Integer.parseInt(args[1]);
// port = Integer.valueOf(args[1]);
}
new ConnectTester().connect(host,port);
}
public void connect(String host,int port){
//創建SocketAddress對象,作爲socket.connect(SocketAddress endPoint,int timeout)的參數
SocketAddress remoteAddr = new InetSocketAddress(host,port);
Socket socket = null;
String result = "";
try{
long begin = System.currentTimeMillis();
socket = new Socket();
socket.connect(remoteAddr, 10000);//超時時間爲1分鐘
long end = System.currentTimeMillis();
result = (end - begin)+"ms";
}catch(BindException e){
result = "Address and port can't be binded";
}catch(UnknownHostException e){
result = "Unknown Host";
}catch(ConnectException e){
result = "Connection Refused";
}catch(SocketTimeoutException e){
result = "TimeOut";
}catch(IOException e){
e.printStackTrace();
}finally{
if(socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println(remoteAddr +":"+result);
}
}