Java基礎_18 | Java中網絡通信程序的設計(url爬蟲,TCP/UDP socket程序,socket文件傳輸程序)

1. Java中的網絡通信程序包

Java提供網絡通信功能的包是java.net包,提供的網絡功能有三大類:

  • URL是三大功能中最高級的一種,通過URL Java程序可以直接送出或讀入網絡上的數據;
  • Socket是傳統網絡程序最常用的方式,可以想象爲兩個不同的程序通過網絡的通信信道;
  • Datagram是更低級的網絡傳輸方式,它把數據的目的記錄在數據包中,然後直接放在網絡上;

本文主要講述前兩種包的使用。

2. URL爬蟲

創建URL類對象要使用java.net包中提供的java.net.URL類的構造方法:

然後調用該對象的openConnection()方法就會返回一個對應URL地址的URLConnection對象,

在建立URLConnection類對象的同時就已經在本級和URL節點之上建立了一條HTTP通道,之後:

  • 可以使用 getInputStream()方法獲得URL節點的信息;
  • 可以使用getOutputStream()方法向URL節點處傳送信息;

示例代碼:

import java.io.IOException;
import java.net.*;
import java.io.*;

public class URLtest {
    public static void main(String[] args) {
        String picture_url = "http://mculover666.cn/image/20190814/NQqt1eRxrl1K.png";

        try {
            // 創建URL對象
            URL pUrl = new URL(picture_url);
            //創建URL
            URLConnection pcUrl = pUrl.openConnection();

            //創建數據流
            InputStream in = pcUrl.getInputStream();
            FileOutputStream fout = new FileOutputStream("E://logo.png");

            //拉取/寫入數據
            int temp;

            while((temp = in.read()) != -1) {
                fout.write(temp);
            }

            //關閉流
            in.close();
            fout.close();
        }
        catch (Exception e) {
            System.out.println("發生異常啦!");
        }
        finally {
            System.out.println("Finish!");
        }
    }
}

爬取到圖片:

3. Socket程序(TCP)

以下Socket程序都是指基於TCP通信的Socket。

Socket通信分爲服務器端和客戶端,在Java中,基於TCP協議實現網絡通信的類有兩個:在
客戶端的Socket類和在服務器端的ServerSocket類。

兩者通信建立過程如下:

  • ① 服務器端生成一個ServerSocket類的實例對象,隨時監聽客戶端的連接請求;
  • ② 客戶端生成一個Socket類的實例對象,併發出連接請求;
  • ③ 服務器端通過accept()方法接收到客戶端的請求後,開闢一個接口與之進行連接,並生成所需的I/O數據流;
  • ④ 通信都是通過一對InputStream()OutputStream()進行的;
  • ⑤ 通信結束後,兩端分別close()對應的Socket接口;

服務端示例代碼如下:

import java.net.*;
import java.io.*;

public class ServerSocketDemo {

    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = null;
        PrintWriter out = null;
        BufferedReader in = null;

        try {
            System.out.println("listening on port: 8000...");
            serverSocket = new ServerSocket(8000);
        } catch (IOException e) {
            System.err.println("Could not listen on port: 8000.");
            System.exit(1);
        }

        Socket clientSocket = null;

        try {
            clientSocket = serverSocket.accept();
            out = new PrintWriter(clientSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        } catch (IOException e) {
            System.err.println("Accept failed.");
            System.exit(1);
        }

        String fromUser;
        int strlen;

        while (true) {
            fromUser= in.readLine();
            strlen=fromUser.length();
            out.println("received string's length is: "+ strlen);
            System.out.println("Server: received string's length is: "+ strlen);
            if(fromUser.equalsIgnoreCase("Bye"))
                break;
        }

        out.close();
        in.close();
        clientSocket.close();
        serverSocket.close();
    }
}

客戶端示例代碼如下:

import java.io.*;
import java.net.*;

public class ClientSocketDemo {
    public static void main(String[] args) throws IOException {

        Socket echoSocket = null;
        PrintWriter out = null;
        BufferedReader in = null;

        try {
            echoSocket = new Socket("127.0.0.1", 8000);
            out = new PrintWriter(echoSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(
                    echoSocket.getInputStream()));
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: taranis.");
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for "
                    + "the connection to: taranis.");
            System.exit(1);
        }

        BufferedReader stdIn = new BufferedReader(
                new InputStreamReader(System.in));
        String userInput;

        while (true){
            userInput = stdIn.readLine();
            out.println(userInput);
            System.out.println("echo: " + in.readLine());

            if(userInput.equalsIgnoreCase("Bye"))
                break;
        }

        out.close();
        in.close();
        stdIn.close();
        echoSocket.close();
    }
}

首先運行服務端:

然後運行客戶端併發送數據:

可以看到收到了服務器迴應,再來看看服務端的輸出:

4. Socket文件傳輸示例程序

server端代碼:

import java.net.*;
import java.io.*;

public class FileServerSocketDemo {
    public static void main(String[] args) {
        try {
            ServerSocket SS = new ServerSocket(8000);
            System.out.println("listening on port 8000...");

            //阻塞等待客戶端連接
            Socket socket = SS.accept();
            System.out.println("client connected!");

            //創建數據流
            DataInputStream dis = new DataInputStream(socket.getInputStream());
            FileOutputStream fo = new FileOutputStream("E://test.txt");
            int temp;
            while ((temp = dis.readInt()) != -1) {
                fo.write(temp);
            }

            //關閉流
            dis.close();
            fo.close();
            socket.close();
            SS.close();
            
        } catch (IOException e) {
            System.out.println("發生異常啦!");
        } finally {
            System.out.println("Finish!");
        }
    }
}

客戶端代碼:

import java.io.*;
import java.net.*;

public class FileClientSocketDemo {
    public static void main(String[] args) {
        try{
            //創建socket並連接服務器
            Socket socket=new Socket("127.0.0.1",8000);

            //創建數據流
            DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
            FileInputStream fi = new FileInputStream("E://sendtest.txt");

            //傳輸文件
            int temp;
            while((temp=fi.read()) !=-1)
                dos.writeInt(temp);

            //關閉流和socket
            dos.close();
            fi.close();
            socket.close();
        }
        catch(IOException e){
            System.out.println("發生異常啦!");
        }
        finally{
            System.out.println ("Finish!");
        }
    }
}

運行結果如下:


接收更多精彩文章及資源推送,歡迎訂閱我的微信公衆號:『mculover666』

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章