網路程式設計Day02

东方语虑發表於2024-09-29

通訊協議

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

問題:非常的複雜

分層:大事化小

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

  • TCP:使用者傳輸協議
  • UDP:使用者資料包協議
  • IP:網路互聯協議

TCP UDP對比

  • TCP:打電話

    • 連線,穩定

    • 三次握手,四次分手

      最少需要三次,保證穩定連線

      最少需要四次,保證連線斷開

    • 客戶端、服務端

    • 傳輸完成,釋放連線,效率低

  • UDP:發簡訊

    • 不連線,不穩定
    • 客戶端、服務端沒有明確的界限
    • 不管有沒有準備好,都可以傳送

TCP

客戶端

  1. 連線伺服器Socket
  2. 傳送訊息
package com.dongfang.ip.lesson02;

import java.io.OutputStream;
import java.net.InetAddress;
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");
            int port = 9999;
            //2.建立一個socket連線
            socket = new Socket(serverIP,port);
            //3.傳送訊息IO流
            os = socket.getOutputStream();
            os.write("你好".getBytes());

        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if (os != null) {
                try{
                    os.close();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }

            if (socket != null) {
                try{
                    socket.close();
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
}

伺服器

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

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 {
            //1.得有一個地址
            serverSocket = new ServerSocket(9999);
            //2.等待客戶端連線過來
            socket = serverSocket.accept();//同一個socket
            //3.讀取客戶端的訊息
            is = socket.getInputStream();

            /*
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1){
                String msg = new String(buffer, 0, len);
                System.out.println(msg);
            }
            */

            //管道流
            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.dongfang.ip.lesson02;

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

public class TCPClientDemo02 {
    public static void main(String[] args) throws Exception {
        //1.建立一個Socket連線
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9000);
        //2.建立一個輸出流
        OutputStream os = socket.getOutputStream();

        //3.讀取檔案
        FileInputStream fis = new FileInputStream(new File("food_big.jpg"));
        //4.寫出檔案
        byte[] buffer = new byte[1024];
        int len;
        while ((len = fis.read(buffer)) != -1) {
            os.write(buffer,0,len);
        }

        //通知伺服器已經傳輸完畢
        socket.shutdownOutput();

        //確定伺服器接收完畢才能夠斷開連線
        InputStream is = socket.getInputStream();
        //String byte[]
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer2 = new byte[1024];
        int len2;
        while ((len2 = is.read(buffer2)) != -1) {
            baos.write(buffer2,0,len2);
        }
        System.out.println(baos.toString());

        //5.關閉資源
        baos.close();
        fis.close();
        os.close();
        is.close();
        socket.close();
    }
}

伺服器端

package com.dongfang.ip.lesson02;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
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());

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

Tomcat

服務端

  • 自定義 S
  • Tomcat伺服器 S :Java後臺開發

客戶端

  • 自定義 C
  • 瀏覽器 B

UDP

不用連線,但是需要知道對方的地址

傳送端

package com.dongfang.ip.lesson03;

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

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

接收端

package com.dongfang.ip.lesson03;

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

//還是要等待客戶端的連線
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(packet.getAddress().getHostAddress());
        System.out.println(new String(packet.getData(),0,packet.getLength()));
        //關閉連線
        socket.close();
    }
}

UDP聊天

迴圈傳送訊息

package com.dongfang.ip.chat;

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

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));

        String data = reader.readLine();
        byte[] datas = data.getBytes();
        DatagramPacket packet = new DatagramPacket(datas,0,datas.length,new InetSocketAddress("localhost",6666));

        socket.send(packet);

        socket.close();
    }
}

迴圈接收訊息

import java.net.DatagramSocket;

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, packet.getLength());
            System.out.println(receiveData);
            if (receiveData.equals("bye")){
                break;
            }
        }
        socket.close();
    }
}

兩個人都可以是傳送方和接收方

URL

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

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

package com.dongfang.ip.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=dongfangyulv&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());//引數
    }
}
package com.dongfang.ip.lesson04;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

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

        //連線到這個資源  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();//斷開連線
    }
}

相關文章