当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);
}
}