Java網路程式設計初探

weixin_33766168發表於2017-11-26

IP地址案例

package ch17;

import javax.swing.text.Style;
import java.net.InetAddress;

/**
 * Created by Jiqing on 2017/1/5.
 */
public class InetAddressTest {
    public static void main(String[] args) throws Exception{
        InetAddress ip = InetAddress.getByName("www.baidu.com");
        // 判斷是否可達
        System.out.println("百度是否可達:"+ip.isReachable(2000));
        // 獲取該例項的IP
        System.out.println(ip.getHostAddress());
        // 根據原始IP地址獲取對應的InetAddress例項
        InetAddress local = InetAddress.getByAddress(new byte[]{127,0,0,1});
        System.out.println("本機是否可達:"+local.isReachable(5000));
        System.out.println(local.getCanonicalHostName());
    }
}

==結果==:
百度是否可達:true
111.13.100.92
本機是否可達:true
127.0.0.1

下載圖片案例

package ch17;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownUtil
{
    // 定義下載資源的路徑
    private String path;
    // 指定所下載的檔案的儲存位置
    private String targetFile;
    // 定義需要使用多少執行緒下載資源
    private int threadNum;
    // 定義下載的執行緒物件
    private DownThread[] threads;
    // 定義下載的檔案的總大小
    private int fileSize;

    public DownUtil(String path, String targetFile, int threadNum)
    {
        this.path = path;
        this.threadNum = threadNum;
        // 初始化threads陣列
        threads = new DownThread[threadNum];
        this.targetFile = targetFile;
    }

    public void download() throws Exception
    {
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5 * 1000);
        conn.setRequestMethod("GET");
        conn.setRequestProperty(
                "Accept",
                "image/gif, image/jpeg, image/pjpeg, image/pjpeg, "
                        + "application/x-shockwave-flash, application/xaml+xml, "
                        + "application/vnd.ms-xpsdocument, application/x-ms-xbap, "
                        + "application/x-ms-application, application/vnd.ms-excel, "
                        + "application/vnd.ms-powerpoint, application/msword, */*");
        conn.setRequestProperty("Accept-Language", "zh-CN");
        conn.setRequestProperty("Charset", "UTF-8");
        conn.setRequestProperty("Connection", "Keep-Alive");
        // 得到檔案大小
        fileSize = conn.getContentLength();
        conn.disconnect();
        int currentPartSize = fileSize / threadNum + 1;//這裡不必一定要加1,不加1也可以
        RandomAccessFile file = new RandomAccessFile(targetFile, "rw");
        // 設定本地檔案的大小
        file.setLength(fileSize);
        file.close();
        for (int i = 0; i < threadNum; i++)
        {
            // 計算每條執行緒的下載的開始位置
            int startPos = i * currentPartSize;
            // 每個執行緒使用一個RandomAccessFile進行下載
            RandomAccessFile currentPart = new RandomAccessFile(targetFile, "rw");
            // 定位該執行緒的下載位置
            currentPart.seek(startPos);
            // 建立下載執行緒
            threads[i] = new DownThread(startPos, currentPartSize, currentPart);
            // 啟動下載執行緒
            threads[i].start();
        }
    }

    // 獲取下載的完成百分比
    public double getCompleteRate()
    {
        // 統計多條執行緒已經下載的總大小
        int sumSize = 0;
        for (int i = 0; i < threadNum; i++)
        {
            sumSize += threads[i].length;
        }
        // 返回已經完成的百分比
        return sumSize * 1.0 / fileSize;
    }

    private class DownThread extends Thread
    {
        // 當前執行緒的下載位置
        private int startPos;
        // 定義當前執行緒負責下載的檔案大小
        private int currentPartSize;
        // 當前執行緒需要下載的檔案塊
        private RandomAccessFile currentPart;
        // 定義已經該執行緒已下載的位元組數
        public int length;

        public DownThread(int startPos, int currentPartSize,RandomAccessFile currentPart)
        {
            this.startPos = startPos;
            this.currentPartSize = currentPartSize;
            this.currentPart = currentPart;
        }

        @Override
        public void run()
        {
            try
            {
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                conn.setConnectTimeout(5 * 1000);
                conn.setRequestMethod("GET");
                conn.setRequestProperty(
                        "Accept",
                        "image/gif, image/jpeg, image/pjpeg, image/pjpeg, "
                                + "application/x-shockwave-flash, application/xaml+xml, "
                                + "application/vnd.ms-xpsdocument, application/x-ms-xbap, "
                                + "application/x-ms-application, application/vnd.ms-excel, "
                                + "application/vnd.ms-powerpoint, application/msword, */*");
                conn.setRequestProperty("Accept-Language", "zh-CN");
                conn.setRequestProperty("Charset", "UTF-8");
                InputStream inStream = conn.getInputStream();
                // 跳過startPos個位元組,表明該執行緒只下載自己負責哪部分檔案。
                inStream.skip(this.startPos);
                byte[] buffer = new byte[1024];
                int hasRead = 0;
                // 讀取網路資料,並寫入本地檔案
                while (length < currentPartSize
                        && (hasRead = inStream.read(buffer)) != -1)
                {
                    currentPart.write(buffer, 0, hasRead);
                    // 累計該執行緒下載的總大小
                    length += hasRead;
                }
                currentPart.close();
                inStream.close();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
}
package ch17;
import java.net.*;

/**
 * Created by Jiqing on 2017/1/5.
 */
public class MultiThreadDown {
    public static void main(String[] args) throws Exception{
        // 初始化DownUtil物件
        final DownUtil downUtil = new DownUtil("http://imgs.aixifan.com/live/1482830873793/1482830873793.jpg","demo.jpg",4);
        // 開始下載
        downUtil.download();
        new Thread(() -> {
           while(downUtil.getCompleteRate() < 1) {
               // 每隔0.01秒查詢一次任務完成進度
               System.out.println("已完成:"+ downUtil.getCompleteRate());
               try {
                   Thread.sleep(10);
               }catch (Exception ex) {}
           }
        }).start();
    }
}

結果:

已完成:0.0
已完成:0.04389803969303463
已完成:0.09210067667384099
已完成:0.16440463214505055
已完成:0.39150257003269945
已完成:0.7543834411326956
已完成:0.9892219080763762

socket案例

服務端

package ch17;

import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;

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

/**
 * Created by Jiqing on 2017/1/6.
 */
public class Server {
    public static void main(String[] args) throws IOException{
        // 建立一個ServerSocket
        ServerSocket ss = new ServerSocket(10000);
        // 採用迴圈不斷地接收來自客戶端的請求
        while(true) {
            // 每當客戶端Socket請求時,伺服器端也產生一個socket
            Socket s = ss.accept();
            PrintStream ps = new PrintStream(s.getOutputStream());
            ps.println("伺服器的新年祝福!");
            ps.close();
            s.close();
        }
    }
}

客戶端

package ch17;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

/**
 * Created by Jiqing on 2017/1/6.
 */
public class Client {
    public static void main(String[] args) throws IOException{
        Socket socket = new Socket("127.0.0.1",10000);
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String line = br.readLine();
        System.out.println("來自伺服器的資料:"+line);
        br.close();
        socket.close();
    }
}

通過ip+埠號進行資料傳輸。先執行伺服器端,再執行客戶端。

結果:
來自伺服器的資料:伺服器的新年祝福!




本文轉自TBHacker部落格園部落格,原文連結:http://www.cnblogs.com/jiqing9006/p/6254559.html,如需轉載請自行聯絡原作者

相關文章