public Socket(String host, int port) throws UnknownHostException, IOException 在Socket类提供的方法中,只有一个UnknownHostException,不能知道倒底是host不正确,还是port不正确,谁有什么办法知道怎么取得这2个不同的错误?
try {
socket = new Socket(host, port);
socket.setSoTimeout(2000);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
response = in.readLine();
if (response.startsWith("+OK")){
//connect ok
}
else{
//the other error
}
}catch(UnknownHostException e) {
//the host error
}catch(SocketException e){
//the port error
}catch(IOException e){
//the other error
}
实际上 setSoTimeout 是这样定义的
setSoTimeout
public void setSoTimeout(int timeout)
throws SocketException
Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time. If the timeout expires, a java.net.SocketTimeoutException is raised, though the Socket is still valid. The option must be enabled prior to entering the blocking operation to have effect. The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.
try {
socket = new Socket(host, port);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
response = in.readLine();
if (response.startsWith("+OK")){
//connect ok
}
else{
//the host error
}
} catch(UnknownHostException ex) {
//the port error
}