获取Socket的信息
getInetAddress():获得远程服务器的IP地址
getPort():获得远程服务器的端口
getLocalAddress():获得客户本地的IP地址
getLocalPort():获得客户本地的端口
getInputStream:获得输入流。如果Socket还没有连接,或者已经关闭,或者已经通过shutdownInout()方法关闭输入流,那么此方法会抛出IOException。
getOutputStream():获得输出流。如果Socket还没有连接,或者已经关闭,或者已经通过shutdownOutpit()方法关闭输出流,那么此方法会抛出IOException。
下面代码能够扫描主机从1到1024之间的端口。
PortScanner
import java.io.IOException;
import java.net.Socket;
public class PortScanner {
public static void main(String args[]) {
String host = "localhost";
if (args.length > 0 ) {
host = args[0];
}
new PortScanner().scan(host);
}
public void scan(String host) {
Socket socket = null;
for (int port = 0; port < 1024; port++) {
try {
socket = new Socket(host, port);
System.out.println("There is a server on Port " + port);
} catch (IOException e) {
// TODO: handle exception
System.out.println("Can't connect to port " + port);
}finally
{
try {
if (socket != null) {
socket.close();
}
} catch (IOException e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
}
}
}
下面代码主要介绍各种异常
ConnectTester
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="www.baidu.com";
int port=80;
if(args.length>1){
host = "www.javathinker.org";
port= 80;
}
new ConnectTester().connect(host,port);
}
public void connect(String host,int port){
SocketAddress remoteAddr=new InetSocketAddress(host,port);
Socket socket=null;
String result="";
try {
long begin=System.currentTimeMillis();
socket = new Socket();
socket.connect(remoteAddr,1000);
long end=System.currentTimeMillis();
result=(end-begin)+"ms";
}catch (BindException e) {
result="Local 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) {
result="failure";
} finally {
try {
if(socket!=null)socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(remoteAddr+" : "+result);
}
}