1. 程式人生 > 實用技巧 >Java網路程式設計筆記

Java網路程式設計筆記

網路程式設計

概述

就是用來實現網路互連的不同計算機上執行的程式間可以進行資料交

計算機網路:

計算機網路是指將地理地理位置不同的具有獨立功能的多臺計算機及其外部裝置,通過通訊線路連線起來,在網路作業系統,網路管理軟體及網路通訊協議的管理和協調下,實現資源共享和資訊傳遞的計算機系統。

網路程式設計的目的:

無線電臺。。。傳播交流資訊,資料交換。通訊

想要達到這個效果需要的是什麼:

  1. 如何準確的定位網路上的一臺主機 192.168.xxx.xxx:埠,定位到這個計算機上的某個資源
  2. 找到了這個主機,如何傳輸資料?

javaweb:網頁程式設計 B/S

網路程式設計:TCP/IP C/S

網路通訊的要素

如何實現網路的通訊?

通訊雙方地址:

  • IP
  • 埠號

規則:網路通訊的協議

TCP/IP參考模型

我們的重點是 傳輸層 TCP UDP

小結:

  1. 網路程式設計中有兩個主要的問題:
  • 如何準確的定位到網路上的一臺或者多臺主機
  • 找到主機之後如何進行通訊
  1. 網路程式設計中的要素
  • IP和埠號 我們要學習 ip.
  • 網路通訊協議 我們要學習 udp tcp.
  1. java中萬物皆物件

IP

ip地址:InetAddress

  • 唯一定位一臺網路上計算機

  • 127.0.0.1: 本機 localhost

  • ip地址的分類

    • ipv4/ipv6(ipconfig)

      • IPV4:127.0.0.1 ,4個位元組組成, 0~255,42億 亞洲4E 30E在北美 2011你就用完了
      • IPV6:fe80::dcaa:44a6:7a3b:6758%16 ,128位。8個無符號整數!
    • 公網(網際網路)-私網(區域網)

      • 19.168.xx.xx 專門給組織內部使用的
      • ABCD類地址
  • 域名:記憶IP問題!

    • IP:www.jd.con

練習程式碼:

package com.lijinyu.lesson01;

import java.net.InetAddress;
import java.net.UnknownHostException;

//測試IP
public class TestInetAddress {
    public static void main(String[] args) {
        try {
            //查詢本地地址
            InetAddress inetAddress01 = InetAddress.getByName("127.0.0.1");
            System.out.println(inetAddress01);
            InetAddress inetAddress2 = InetAddress.getByName("localhost");
            System.out.println(inetAddress01);
            InetAddress inetAddress3 = InetAddress.getLocalHost();
            System.out.println(inetAddress01);
            //查詢白度id地址
            InetAddress inetAddress4 = InetAddress.getByName("www.baidu.com");
            System.out.println(inetAddress4);

            //常用方法
            System.out.println(inetAddress4.getAddress());
            System.out.println(inetAddress4.getCanonicalHostName()); //規範名
            System.out.println(inetAddress4.getHostAddress());//ip
            System.out.println(inetAddress4.getHostName());//域名,或者自己電腦的名字
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

埠表示計算機上的一個程式的程序

  • 不同的程序有不同的埠號!用來區分軟體

  • 一般埠被規定0~65535

  • TCP,UDP:65535*2 tcp:80那麼udp:80可以用嘛?---不能。 單個協議下,埠號不能衝突

  • 埠分類

    • 公有埠0~1023

      • HTTP:80
      • HTTPS:443
      • FTP:21
      • Telent:23
    • 程式註冊埠:1024~49151,用來分配給使用者或者程式的

      • Tomcat:8080
      • MySQL:3306
      • Oracle:1521
    • 動態、私有埠:49152~65535

      Doc命令:

      netstat -ano  # 檢視所有的埠
      netstat -ano|findstr "5900/xx" # 檢視指定的埠
      tasklist|findstr "8696/xx" # 檢視指定埠的程序
      檢視任務程序管理器快捷鍵的其中一種:ctrl+shift+Esc
      

練習程式碼:

package com.lijinyu.lesson01;

import java.net.InetSocketAddress;
import java.net.SocketAddress;

// 查詢埠等
public class TestInetSocketAddress {
    public static void main(String[] args) {
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 8080);
        InetSocketAddress inetSocketAddress2 = new InetSocketAddress("localhost", 8080);
        System.out.println(inetSocketAddress);
        System.out.println(inetSocketAddress2);

        System.out.println(inetSocketAddress.getAddress());
        System.out.println(inetSocketAddress.getHostName());  //地址
        System.out.println(inetSocketAddress.getPort());   //埠
    }
}

通訊協議

協議:約定,好讓我們能夠交流

** 網路通訊協議:**速率,傳輸位元速率,程式碼結構,傳輸控制......

問題:非常的複雜。

大事化小:分層概念!

TCP/IP協議簇:實際上是一組協議

重要:

  • TCP:使用者傳輸協議 (比如打電話,交流)
  • UDP:使用者資料報協議(比如郵件等。)

出名的協議:

  • TCP
  • IP:網路互連協議

TCP udp 對比:

TCP:就相當於打電話

  • 連線,穩定

  • 三次握手 四次揮手

# 至少三次對話才能握手有交流
最少需要三次,保證穩定連線!
A:你瞅啥?
B:瞅你咋地?
A:幹一場!

# 至少四次揮手,才能保證斷開了
A:我要走了
B:我真的你要走了
B:你真的真的走了嗎
A:我真的要走了。

  • 客戶端、服務端
  • 傳輸完成,釋放連線,效率低

UDP:就像是發簡訊

  • 不連線,不穩定
  • 客戶端、服務端:沒有明確的界限
  • 不管有沒有準備好,都可以發給你..
  • 就如導彈攻擊
  • DDOS:洪水攻擊!(飽和攻擊)

TCP

客戶端

  1. 連線伺服器 Socket

  2. 傳送訊息

    package com.lijinyu.lesson02;
    
    import java.io.IOException;
    import java.io.OutputStream;
    import java.net.InetAddress;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.net.UnknownHostException;
    
    //客戶端
    public class TcpClientDemo01 {
        public static void main(String[] args) {
            Socket socket = null;
            OutputStream os = null;
            try {
                //1.要知道伺服器的地址
                InetAddress serverIP = InetAddress.getByName("127.0.0.1");
                //2.埠號
                int port = 9999;
                //3.建立一個socket連線
                socket = new Socket(serverIP, port);
                //4.傳送訊息  IO流
                os = socket.getOutputStream();
                os.write("你好,歡迎學習狂神說".getBytes());
    
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (os != null) {
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
    
            }
    
    
        }
    }
    

伺服器

  1. 建立服務埠 ServerSocket
  2. 等待使用者的連線 accept
  3. 接收使用者的訊息
package com.lijinyu.lesson02;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

//伺服器
public class TcpServerDemo01 {
    public static void main(String[] args) {
        ServerSocket serverSocket=null;
        Socket socket =null;
        InputStream is=null;
        ByteArrayOutputStream baos=null;

        try {
            //我得有一個地址
             serverSocket = new ServerSocket(9999);
            //2. 等待客戶端連線過來
            socket = serverSocket.accept();
            // 3.讀取客戶端的訊息
             is=socket.getInputStream();
             
             //管道流
            baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while((len=is.read(buffer))!=-1){
                baos.write(buffer,0,len);
            }
            System.out.println(baos.toString());


        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //關閉資源
            if(baos!=null){
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }
}

檔案上傳

服務端:

package com.lijinyu.lesson02;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

//服務端
public class TcpServerDemo02 {
    public static void main(String[] args) throws Exception {
        //1. 建立服務(埠)
        ServerSocket serverSocket = new ServerSocket(9000);
        //2.監聽客戶端的連線
        Socket socket = serverSocket.accept();
        //3.獲取輸入流
        InputStream is = socket.getInputStream();
        //4.檔案輸出
        FileOutputStream fos = new FileOutputStream(new File("receive.jpg"));
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
        }
        //通知客戶端我接收完了
        OutputStream os = socket.getOutputStream();
        os.write("我接收完畢了,你可以斷開了".getBytes());


        //關閉資源
        fos.close();
        is.close();
        socket.close();
        serverSocket.close();
    }
}

客戶端:

package com.lijinyu.lesson02;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

//客戶端
public class TcoClientDemo02 {
    public static void main(String[] args) throws Exception {
        //1.建立一個Socket連線
        Socket socket = new Socket(InetAddress.getByName("127.0.01"), 9000);

        //2.建立一個輸出流
        OutputStream os = socket.getOutputStream();

        //3.讀取檔案
        FileInputStream fis = new FileInputStream(new File("李晉宇.jpg"));

        //4.寫出檔案
        byte[] buffer = new byte[1024];
        int len;
        while ((len = fis.read(buffer)) != -1) {
            os.write(buffer, 0, len);
        }
        //通知伺服器,我結束了
        socket.shutdownOutput();//傳輸完了
        //確定伺服器接收完畢,才能斷開連線
        InputStream inputStream = socket.getInputStream();
        // String byte[]
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        byte[] buffer2 = new byte[2014];
        int len2;
        while ((len2 = inputStream.read(buffer2)) != -1) {
            baos.write(buffer2, 0, len2);
        }
        System.out.println(baos.toString());
        //5.關閉資源
        baos.close();
        inputStream.close();
        socket.close();
        os.close();
        fis.close();

    }
}

Tomcat

執行Tomcat之前要把Java環境配置好了才可以。

服務端

  • 自定義 S
  • Tomcat伺服器S

客戶端

  • 自定義C
  • 瀏覽器B

UDP訊息傳送

發簡訊:不用連線,需要知道對方的地址!

接收端:

package com.lijinyu.lesson03;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

//還是要等待客戶端的連線!
public class UdpServerDemo01 {
    public static void main(String[] args) throws Exception {
        //開放埠
        DatagramSocket socket = new DatagramSocket(9090);
        //接收資料包
        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);

        socket.receive(packet); //阻塞接收
        System.out.println(new String(packet.getData(), 0, packet.getLength()));
        System.out.println(packet.getAddress().getHostAddress());
        socket.close();

    }
}

傳送端:

package com.lijinyu.lesson03;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

//不需要連線伺服器
public class UdpClientDemo01 {
    public static void main(String[] args) throws Exception {
        //1.建立一個Socket
        DatagramSocket socket = new DatagramSocket();
        //2.建個包
        String msg = "你好,伺服器";
        //傳送給誰
        InetAddress localhost = InetAddress.getByName("localhost");
        int port = 9090;
        //資料,資料長度起始,要傳送給誰
        DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, localhost, port);
        //3.傳送包
        socket.send(packet);
        //關閉
        socket.close();
    }
}

UDP聊天實現(迴圈傳送接收訊息)

傳送訊息:

package com.lijinyu.chat;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

public class UdpSenderDemo01 {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(8888);

        //準備資料:控制檯讀取System,in
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            String data = reader.readLine();
            byte[] datas = data.getBytes();

            DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress("localhost", 6666));
            socket.send(packet);
            if (data.equals("bye")) {
                break;
            }
        }


        socket.close();

    }
}

接收訊息:

package com.lijinyu.chat;

import javax.xml.stream.FactoryConfigurationError;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpReceiveDemo01 {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(6666);

        while (true) {
            //準備接受包裹
            byte[] container = new byte[1024];
            DatagramPacket packet = new DatagramPacket(container, 0, container.length);
            socket.receive(packet);//阻塞試接受包裹

            //斷開連線 bye
            byte[] data = packet.getData();
            String receiveData = new String(data, 0, data.length);
            System.out.println(receiveData);
            if (receiveData.equals("bye")) {
                break;
            }

        }
        socket.close();

    }
}

UDP多執行緒線上諮詢

線上諮詢,兩個人都可以是傳送方,也都可以是接收方

接收:

package com.lijinyu.chat;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class TalkReceive implements Runnable {
    DatagramSocket socket = null;
    private int port;
    private String msgFrom;

    public TalkReceive(int port, String masFrom) {
        this.port = port;
        this.msgFrom = masFrom;
        try {
            socket = new DatagramSocket(port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    public TalkReceive(DatagramSocket socket) {
        this.socket = socket;
    }


    @Override
    public void run() {
        while (true) {
            //準備接受包裹
            try {
                byte[] container = new byte[1024];
                DatagramPacket packet = new DatagramPacket(container, 0, container.length);
                socket.receive(packet);//阻塞試接受包裹

                //斷開連線 bye
                byte[] data = packet.getData();
                String receiveData = new String(data, 0, data.length);
                System.out.println(msgFrom + ":" + receiveData);
                if (receiveData.equals("bye")) {
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        socket.close();
    }
}

傳送

package com.lijinyu.chat;

import javax.sound.sampled.Port;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

public class TalkSend implements Runnable {
    DatagramSocket socket = null;
    BufferedReader reader = null;

    private int fromPort;
    private String toIP;
    private int toPort;

    public TalkSend(int fromPort, String toIP, int toPort) {
        this.fromPort = fromPort;
        this.toIP = toIP;
        this.toPort = toPort;
        try {
            socket = new DatagramSocket(fromPort);
            reader = new BufferedReader(new InputStreamReader(System.in));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public TalkSend() {

    }

    @Override
    public void run() {


        while (true) {

            try {
                String data = reader.readLine();
                byte[] datas = data.getBytes();

                DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress(this.toIP, this.toPort));
                socket.send(packet);
                if (data.equals("bye")) {
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }


        socket.close();
    }
}

老師與學生

package com.lijinyu.chat;

public class TalkStudent {
    public static void main(String[] args) {
        //開啟兩個執行緒
        new Thread(new TalkSend(7777, "localhost", 9999)).start();
        new Thread(new TalkReceive(8888, "老師")).start();
    }
}


package com.lijinyu.chat;

public class TalkTeacher {
    public static void main(String[] args) {
        new Thread(new TalkSend(5555, "localhost", 8888)).start();
        new Thread(new TalkReceive(9999, "學生 ")).start();
    }
}

URL

統一資源定位符:定位資源的,定位網際網路上的某一個資源

DNS域名解析 www.baidu.com xxx.xxx.xxx

協議://ip地址:埠號/專案名/資源

瀏覽本機

package com.lijinyu.lesson04;

import java.net.MalformedURLException;
import java.net.URL;

public class URLDemo01 {
    public static void main(String[] args) throws MalformedURLException {
        URL url = new URL("http://localhost:8080/helloworld/index.jsp?username=lijinyu&password=123");
        System.out.println(url.getProtocol());//協議
        System.out.println(url.getHost()); //主機ip
        System.out.println(url.getPort());//埠
        System.out.println(url.getPath());//檔案
        System.out.println(url.getFile());//全路徑
        System.out.println(url.getQuery());//引數
    }
}

下載資源:(url那裡可以換成網上找的)

package com.lijinyu.lesson04;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class UrlDown {
    public static void main(String[] args) throws IOException {
        // 1.下載地址
        URL url = new URL("http://localhost:8080/lijinyu/SecurityFile.txt");

        //2.連線到這個資源 HTTP
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        InputStream inputStream = urlConnection.getInputStream();

        FileOutputStream fos = new FileOutputStream("SecurityFile.txt");

        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) != -1) {
            fos.write(buffer, 0, len);//寫出這個資料
        }
        fos.close();
        inputStream.close();
        urlConnection.disconnect();//斷開連線


    }
}

筆記是根據狂神說Java的課程所做的筆記!