Java 网络实例


  • 获取指定主机的IP地址
  • 查看端口是否已使用
  • 获取本机ip地址及主机名
  • 获取远程文件大小
  • 查看主机指定文件的最后修改时间
  • 使用 Socket 连接到指定主机
  • 网页抓取
  • 获取 URL响应头的日期信息
  • 获取 URL 响应头信息
  • 解析 URL

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Map;
import java.util.Set;

public class Internet {

    public static void main(String[] args) {

        getIP(); // 获取指定主机的IP地址

        portIf("localhost"); // 查看端口是否已使用

        local(); // 获取本机ip地址及主机名

        getSize(); // 获取远程文件大小

        getLast(); // 查看主机指定文件的最后修改时间

        webPing(); // 使用 Socket 连接到指定主机

        webCrawl(); // 网页抓取

        getDate(); // 获取 URL响应头的日期信息

        getHead(); // 获取 URL 响应头信息

        alyURL(); // 解析 URL
    }

    private static void getIP() {
        InetAddress address = null;
        try {
            // 使用 InetAddress 类的 InetAddress.getByName() 方法来获取指定主机(网址)的IP地址
            address = InetAddress.getByName("www.google.com");
        } catch (UnknownHostException e) {
            // System.exit(2);
        }
        System.out.println(address.getHostName() + "=" + address.getHostAddress());
        // System.exit(0);
    }

    private static void portIf(String host) {
        @SuppressWarnings("unused")
        Socket sk;
        for (int i = 79; i < 81; i++) {
            try {
                System.out.println("查看 " + i);
                sk = new Socket(host, i);
                System.out.println("端口 " + i + " 已被使用");
            } catch (UnknownHostException e) {
                System.out.println("Exception occured " + e);
                break;
            } catch (IOException e) {

            }

        }
    }

    // 使用 InetAddress 类的 getLocalAddress() 方法获取本机ip地址及主机名
    private static void local() {
        try {
            InetAddress addr = InetAddress.getLocalHost();
            System.out.println("Local HostAddress:" + addr.getHostAddress());
            System.out.println("Local host name: " + addr.getHostName());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    private static void getSize() {
        int size;
        URL url;
        try {
            url = new URL("http://www.runoob.com/wp-content/themes/runoob/assets/img/newlogo.png");
            URLConnection conn = url.openConnection();
            size = conn.getContentLength();
            if (size < 0)
                System.out.println("无法获取文件大小。");
            else
                System.out.println("文件大小为:" + size + " bytes");
            conn.getInputStream().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void getLast() {
        try {
            URL u = new URL("http://127.0.0。1/test");
            URLConnection uc;
            uc = u.openConnection();
            uc.setUseCaches(false);
            long t = uc.getLastModified();
            System.out.println("test 文件最后修改时间: " + t);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 使用 net.Socket 类的 getInetAddress() 方法来连接到指定主机
    private static void webPing() {
        try {
            InetAddress addr;
            Socket sock = new Socket("www.runoob.com", 80);
            addr = sock.getInetAddress();
            System.out.println("连接到 " + addr);
            sock.close();
        } catch (IOException e) {
            System.out.println("无法连接 ");
            System.out.println(e);
        }
    }

    private static void webCrawl() {
        URL url;
        try {
            url = new URL("http://www.runoob.com");
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            BufferedWriter writer;
            writer = new BufferedWriter(new FileWriter("data.html"));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
                writer.write(line);
                writer.newLine();
            }
            reader.close();
            writer.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void getDate() {
        try {
            URL url = new URL("http://www.runoob.com");
            HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
            long date = httpCon.getDate();
            if (date == 0)
                System.out.println("无法获取信息。");
            else
                System.out.println("Date: " + new Date(date));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void getHead() {
        try {
            URL url = new URL("http://www.runoob.com");
            URLConnection conn = url.openConnection();

            Map<String, ?> headers = conn.getHeaderFields();
            Set<String> keys = headers.keySet();
            for (String key : keys) {
                String val = conn.getHeaderField(key);
                System.out.println(key + "    " + val);
            }
            System.out.println(conn.getLastModified());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void alyURL() {
        URL url;
        try {
            url = new URL("http://www.runoob.com/html/html-tutorial.html");
            System.out.println("URL 是 " + url.toString());
            System.out.println("协议是 " + url.getProtocol());
            System.out.println("文件名是 " + url.getFile());
            System.out.println("主机是 " + url.getHost());
            System.out.println("路径是 " + url.getPath());
            System.out.println("端口号是 " + url.getPort());
            System.out.println("默认端口号是 " + url.getDefaultPort());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

    }
}

  • Socket 实现多线程服务器程序

import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class MultiThreadServer implements Runnable {

    Socket csocket;

    MultiThreadServer(Socket csocket) {
        this.csocket = csocket;
    }

    public static void main(String args[]) throws Exception {
        @SuppressWarnings("resource")
        ServerSocket ssock = new ServerSocket(1234);
        System.out.println("Listening");
        while (true) {
            Socket sock = ssock.accept();
            System.out.println("Connected");
            new Thread(new MultiThreadServer(sock)).start();
        }
    }

    public void run() {
        try {
            PrintStream pstream = new PrintStream(csocket.getOutputStream());
            for (int i = 100; i >= 0; i--) {
                pstream.println(i + " bottles of beer on the wall");
            }
            pstream.close();
            csocket.close();
        } catch (IOException e) {
            System.out.println(e);
        }
    }
}

  • ServerSocket 和 Socket 通信实例 - 如何实现客户端发送消息到服务器,服务器接收到消息并读取输出,然后写出到客户端客户端接收到输出
    1. 建立服务器端 - Server.java
      • 服务器建立通信ServerSocket
      • 服务器建立Socket接收客户端连接
      • 建立IO输入流读取客户端发送的数据
      • 建立IO输出流向客户端发送数据消息
    2. 建立客户端 - Client.java
      • 创建Socket通信,设置通信服务器的IP和Port
      • 建立IO输出流向服务器发送数据消息
      • 建立IO输入流读取服务器发送来的数据消息

  • Server.java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) {
        try {
            ServerSocket ss = new ServerSocket(8888);
            System.out.println("启动服务器....");
            Socket s = ss.accept();
            System.out.println("客户端:" + s.getInetAddress().getLocalHost() + "已连接到服务器");

            BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            // 读取客户端发送来的消息
            String mess = br.readLine();
            System.out.println("客户端:" + mess);
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
            bw.write(mess + "\n");
            bw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • Client.java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {
    public static void main(String[] args) {
        try {
            Socket s = new Socket("127.0.0.1", 8888);

            // 构建IO
            InputStream is = s.getInputStream();
            OutputStream os = s.getOutputStream();

            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
            // 向服务器端发送一条消息
            bw.write("测试客户端和服务器通信,服务器接收到消息返回到客户端\n");
            bw.flush();

            // 读取服务器返回的消息
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String mess = br.readLine();
            System.out.println("服务器:" + mess);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • 测试结果

编译运行


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值