1.Socket简介
客户端与服务端连接成功则返回Socket对象,否则IOException
2.Socket连接超时
Socket socket = new Socket();
SocketAddress address = new InetSocketAddress("",80);
// 时间设置为0 则不会超时
socket.connect(address,5000);
3.设置服务器的地址
使用String
InetAddress类表示服务器IP地址
InetAddress.getLocalHost();
InetAddress.getByName();
4.一个扫描端口的示例
- 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("Threa is a server on port"+ port);
- } catch (UnknownHostException e) {
- System.out.println("找不到主机");
- } catch (IOException e) {
- System.out.println("无法连接的端口"+ port);
- } finally{
- if(socket!=null)
- try {
- socket.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }