Socket构造方法如下:
1 Socket() 2 //Creates an unconnected socket, with the system-default type of SocketImpl. 3 4 Socket(InetAddress address, int port) 5 //Creates a stream socket and connects it to the specified port number at the 6 //specified IP address. 7 8 Socket(InetAddress host, int port, boolean stream) 9 //Deprecated. 10 //Use DatagramSocket instead for UDP transport. 11 12 Socket(InetAddress address, int port, InetAddress localAddr, int localPort) 13 //Creates a socket and connects it to the specified remote address on the 14 //specified remote port. 15 16 Socket(Proxy proxy) 17 //Creates an unconnected socket, specifying the type of proxy, if any, that 18 //should be used regardless of any other settings. 19 20 Socket(SocketImpl impl) 21 //Creates an unconnected Socket with a user-specified SocketImpl. 22 23 Socket(String host, int port) 24 //Creates a stream socket and connects it to the specified port number on the 25 named host. 26 27 Socket(String host, int port, boolean stream) 28 //Deprecated. 29 //Use DatagramSocket instead for UDP transport. 30 31 Socket(String host, int port, InetAddress localAddr, int localPort) 32 //Creates a socket and connects it to the specified remote host on the specified 33 //remote port.
除了第一个无参,其余构造方法都试图建立与服务器的连接,如果成功则返回Socket对象,否在抛出异常。
根据以上构造方法来创建一个类,用于扫描主机上1-1024之间的端口是否被服务器程序监听(如果被监听,就可以返回Socket对象)。代码如下:
import java.io.IOException; import java.net.Socket; public class PortScanner { public static void main(String[] args) { String host="localhost"; new PortScanner().scan(host); } public void scan(String host){ Socket socket=null; for(int port=1;port<=1024;port++){ try{ socket=new Socket(host,port); System.out.println("There is a server on port "+port); }catch(IOException e){ System.out.println("Can't connect to port "+port); }finally{ if(socket!=null){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } } }
2.1.1 设定等待建立连接的超时时间
当需要设定连接超时时间时,则需要调用Socket的无参构造函数。
Socket socket = new Socket(); //SocketAddress 提供不可变对象,供套接字用于绑定、连接或用作返回值。 SocketAddress remoteAddr = new InetSocketAddress("localhost",8000); //超时未连接时,会抛出超时异常。 socket.connect(remoteAddr,60000);//毫秒为单位,0表示用于不超时
2.1.2 设定服务器地址
除了第一个无参构造函数,其余都需要提供服务器IP或主机名,以及端口号。
1 Socket(InetAddress address,int port) //第一个参数表示主机IP地址 2 Socket(String host,int port) //第一个表示主机名