Crazy God says Java -- Notes on network programming

Posted by SyWill on Fri, 28 Jan 2022 09:07:24 +0100

Network programming

1. General

Mail:

  • Computer network: computer network refers to Geography Multiple sets with independent functions in different positions computer And its external equipment are connected through communication lines Network operating systemNetwork management software and Network communication protocol Under the management and coordination of resource sharing And information transmission computer system.
  • The purpose of network programming: radio station... Dissemination and exchange of information, data exchange and communication.
  • What is needed to achieve this effect:
    1. How to accurately locate a host 192.168.16.124: port on the network and locate a resource on the computer.
    2. After finding the host, how to transmit data?
  • Javaweb: Web programming, B/S architecture
  • Network programming: TCP/IP, C/S

2. Network communication elements

How to realize network communication?

  • Address of both parties:
    • ip: 192.168.16.124
    • Port: 5900
  • Rule: protocol of network communication: TCP/IP

Summary:

  1. There are two main problems in network programming:
    • How to accurately locate one or more hosts on the network;
    • How to communicate after finding the host;
  2. Elements in network programming:
    • IP and port number:
    • Network communication protocol: UDP, TCP
  3. Everything is object

3.IP

IP address: InetAddress

  • Uniquely locate a computer on a network

  • 127.0.0.1: local localhost

  • Parent class of ip address

    • IPV4: 127.0.0.1, composed of 4 bytes., 0 ~ 255, 4.2 billion ~; Three billion are in North America and 400 million in Asia. Exhausted in 2011;
    • IPV6: fe80::f0e0:7383:ad8e:f32f%3128 bits. 8 unsigned integers
    2406:da18:ddf:4000:67d5:b226:cad7:125b
    
  • Public network (Internet) – private network (LAN)

    • ABCD address

    • 192.168.xx.xx, for internal use of the organization.

  • Domain name: memory IP problem!

    • IP: www.vip.com
package github.Web;

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

/**
 * @author subeiLY
 * @create 2021-06-06 10:09
 */
public class TestInetAddress {
    public static void main(String[] args) {
        try{
            // Query local address
            InetAddress inetAddress1 = InetAddress.getByName("127.0.0.1");
            System.out.println(inetAddress1);
            InetAddress inetAddress2 = InetAddress.getByName("localhost");
            System.out.println(inetAddress2);
            InetAddress inetAddress3 = InetAddress.getLocalHost();
            System.out.println(inetAddress3);

            // Query website IP address
            InetAddress inetAddress = InetAddress.getByName("www.taobao.com");
            System.out.println(inetAddress);

            // common method
//            System.out.println(inetAddress.getAddress());   //  A byte array is returned
            System.out.println(inetAddress.getCanonicalHostName());    // Canonical name
            System.out.println(inetAddress.getHostAddress());  // IP
            System.out.println(inetAddress.getHostName()); // Domain name, or the name of your own computer

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

    }
}

4. Port

  • Port represents the process of a program on the computer;

  • Different processes have different port numbers! Used to distinguish software!

  • Specified 0 ~ 65535

  • tcp, UDP: 65535 * 2 ports tcp: 80 udp: 80 port numbers cannot conflict under a single protocol

  • Port classification

    • Ports 0 ~ 1023 are used by built-in processes
      • HTTP: 80
      • HTTP: 443 for example, visit https://www.baidu.com COM: 443 visit Baidu
      • FTP: 21
      • TELENT: 23
    • Program registration port: 1014-49151, assigned to users and programs
      • Tomcat: 8080
      • MySql: 3306
      • Oracle: 1521
    • Dynamic and private ports: 49152 ~ 65535
netstat -ano #View all ports
netstat -nao|findstr "7808" #View the specified port
tasklist|findstr "8696"

package github.Web;

import java.net.InetSocketAddress;

/**
 * @author subeiLY
 * @create 2021-06-06 10:34
 */
public class TestInetSocketAddress {
    public static void main(String[] args) {
        InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1", 8080);
        InetSocketAddress socketAddress2 = new InetSocketAddress("localhost", 8080);
        System.out.println(socketAddress);
        System.out.println(socketAddress2);

        System.out.println(socketAddress.getAddress());
        System.out.println(socketAddress.getHostName());    // address
        System.out.println(socketAddress.getPort());    // port
    }
}

5. Communication protocol

Agreement: agreement, just like the Chinese people speak Mandarin

Network communication protocol: rate, transmission code rate, code structure, transmission control

Problem: very complex

Make big things small: layering

TCP/IP protocol cluster: it is actually a group of protocols

Important:

  • TCP: user transport protocol
  • UDP: User Datagram Protocol

Famous agreement:

  • TCP:
  • IP: network interconnection protocol

TCP UDP comparison

  • TCP: call

    • Connection, stable

    • Three handshakes and four waves

      At least three times to ensure a stable connection!
      A: What are you looking at?
      B: What do you think?
      A: Have a fight
      
      A: I'm breaking up
      B: I know you're breaking up
      B: Are you really breaking up?
      A: I'm really breaking up
      
    • Client, server

    • The transmission is completed, the connection is released, and the efficiency is low

  • UDP; send message

    • Not connected, unstable
    • Client and server: there is no clear solution
    • It can be sent to you whether it is ready or not
    • DDOS: flood attack! Send garbage packets to block the line (saturation attack)

6.TCP

Start the server first and then the client!!!!

client

  • Connect to the server Socket
  • send message
package github.Web.Demo02;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

/**
 * @author subeiLY
 * @create 2021-06-06 11:08
 */
// client
public class TCPClientDemo01 {
    public static void main(String[] args) {
        Socket accept = null;
        OutputStream os = null;

        try {
            // 1. Know the address of the server
            InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
            int port = 9999;
            // 2. Create a socket link
            accept = new Socket(inetAddress,port);
            // 3. Send information IO stream
            os = accept.getOutputStream();
            os.write("That's it. What the hell?".getBytes());
        }catch (Exception e){
            e.printStackTrace();
        } finally {
            // close resource
            if(os != null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(accept != null){
                try {
                    accept.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Server side

  • Establish service port ServerSocket
  • Wait for the user's connection accept
  • Receive messages from users
package github.Web.Demo02;

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

/**
 * @author subeiLY
 * @create 2021-06-06 11:22
 */
// Server
public class TCPServerDemo01 {
    public static void main(String[] args) {

        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;

        try{
            // 1. Have an address
            serverSocket = new ServerSocket(9999);
            // 2. Wait for the client to connect
            socket = serverSocket.accept();
            // 3. Read the message from the client
            is = socket.getInputStream();

           /*
           //There will be Chinese garbled code when discarded
           byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(bytes)) != -1){
                String s = new String(buffer,0,len);
                System.out.println(s);
            }
            */

            // Pipe flow
            baos = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            System.out.println(baos.toString());

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // close resource
            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();
                }
            }
        }
    }
}

1. File upload

  • client
package github.Web.Demo02;

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

/**
 * @author subeiLY
 * @create 2021-06-06 13:13
 */
// client
public class TCPClientDemo02 {
    public static void main(String[] args) throws Exception {
        // 1. Establish connection
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9000);
        // 2. Create output stream
        OutputStream os = socket.getOutputStream();
        // 3. Read the file
        FileInputStream stream = new FileInputStream(new File("subei.jpg"));
        // 4. Output test documents
        byte[] buffer = new byte[1024];
        int len = 0;
        while((len = stream.read(buffer)) != -1){
            os.write(buffer,0,len);
        }
        // 5. Notify the server that sending is complete
        socket.shutdownOutput();
        // 6. Confirm that the server has received and disconnect
        InputStream inputStream = socket.getInputStream();

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer2 = new byte[1024];
        int len2 = 0;
        while((len2 = stream.read(buffer2)) != -1){
            byteArrayOutputStream.write(buffer2,0,len2);
        }

        System.out.println(byteArrayOutputStream);

        // 7. Close flow
        byteArrayOutputStream.close();
        inputStream.close();
        stream.close();
        os.close();
        socket.close();

    }
}
  • Server
package github.Web.Demo02;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author subeiLY
 * @create 2021-06-06 13:13
 */
// The server
public class TCPServerDemo02 {
    public static void main(String[] args) throws Exception{
        // 1. Create a server address
        ServerSocket socket = new ServerSocket(9000);
        // 2. Listen for customer connections
        Socket accept = socket.accept();    // Blocking monitoring, which can wait for users to connect
        // 3. Get input stream
        InputStream is = accept.getInputStream();
        // 4. Determine the location of documents
        FileOutputStream fileOutputStream = new FileOutputStream("resort.jpg");

        // 5. Write file
        byte[] buffer = new byte[1024];
        int len = 0;
        while((len = is.read(buffer)) != -1){
            fileOutputStream.write(buffer,0,len);
        }

        // 6. Notify the client that the collection is complete
        OutputStream outputStream = accept.getOutputStream();
        outputStream.write("The server has collected successfully, please disconnect!".getBytes());

        // 7. Close flow
        outputStream.close();
        fileOutputStream.close();
        is.close();
        accept.close();
        socket.close();

    }
}

2. Getting to know Tomcat

Tomcat

Tomcat garbled Code: conf \ logging Properties change UTF-8 to GBK

Server

  • Custom S
  • Tomcat server S: Java background development

client

  • Custom C
  • Browser B

7.UDP

Texting: don't connect. You need to know the other party's address

1. Send message

package github.Web.Demo03;

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

/**
 * @author subeiLY
 * @create 2021-06-06 13:25
 */
// No need to connect to the server
public class UDPClientDemo01 {
    public static void main(String[] args) throws Exception{
        // 1. Create a Socket
        DatagramSocket socket = new DatagramSocket();
        // 2. Build a package
        String msg = "Hello, server!";
        InetAddress localhost = InetAddress.getByName("localhost");
        int port = 9090;

        // Data, starting from the length of the data, to whom
        DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0,msg.getBytes().length,localhost,port);

        // 3. Send packet
        socket.send(packet);

        // 4. Close flow
        socket.close();

    }
}
package github.Web.Demo03;

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

/**
 * @author subeiLY
 * @create 2021-06-06 13:26
 */
// Or do you need a link from the client
public class UDPServerDemo01 {
    public static void main(String[] args) throws Exception{
        // 1. Open port
        DatagramSocket socket = new DatagramSocket(9090);
        // 2. Receive packets
        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);

        socket.receive(packet); // Blocking acceptance
        System.out.println(packet.getAddress().getHostAddress());
        System.out.println(new String(packet.getData()));
        // 3. Close the connection
        socket.close();

    }
}

2. Send message circularly

package github.Web.Demo03;

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

/**
 * @author subeiLY
 * @create 2021-06-06 14:06
 */
public class UDPSenderDemo01 {
    public static void main(String[] args) throws Exception{
        DatagramSocket socket = new DatagramSocket(8888);

        // Preparing data: console reading
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        while(true) {
            String data = reader.readLine();
            byte[] buffer = data.getBytes();
            DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length, new InetSocketAddress("localhost", 9090));

            // Send packet
            socket.send(packet);
            if (data.equals("bye")) {
                break;
            }
        }

        // Close socket
        socket.close();

    }
}
package github.Web.Demo03;

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

/**
 * @author subeiLY
 * @create 2021-06-06 14:06
 */
public class UDPReceiveDemo01 {
    public static void main(String[] args) throws Exception{
        // Open port
        DatagramSocket socket = new DatagramSocket(6666);

        while (true) {

            // Ready to receive package
            byte[] container = new byte[1024];
            DatagramPacket packet = new DatagramPacket(container, 0, container.length);
            socket.receive(packet);


            byte[] data = packet.getData();
            String receiveData = new String(data);
            System.out.println(receiveData);


            if (receiveData.equals("bye")) {
                break;
            }
        }

        // Close socket
        socket.close();

    }
}

Online consultation: both can be the sender or the receiver (with multithreading)

  • Sender
package github.Web.Demo04;

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;

/**
 * @author subeiLY
 * @create 2021-06-06 14:22
 */
public class TalkSend implements Runnable {
    DatagramSocket socket = null;
    BufferedReader reader = null;

    private int    formPort;
    private String hostname;
    private int    toPort;

    public TalkSend(int formPort, String hostname, int toPort) {
        this.formPort = formPort;
        this.hostname = hostname;
        this.toPort = toPort;

        try {
            socket = new DatagramSocket(formPort);
            reader = new BufferedReader(new InputStreamReader(System.in));
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {

        while (true) {
            try {
                String s = reader.readLine();
                byte[] buffer = s.getBytes();
                DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length,
                        new InetSocketAddress(hostname, toPort));

                // Send packet
                socket.send(packet);
                if (s.equals("bye")) {
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // Close socket
        socket.close();
    }
}
  • receiving end
package github.Web.Demo04;

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

/**
 * @author subeiLY
 * @create 2021-06-06 14:22
 */
public class TalkReceive implements Runnable{
    DatagramSocket socket = null;

    private int port;

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

    @Override
    public void run() {
        //Open port

        // Receive packet
        while (true){
            try {
                byte[] container = new byte[1024];
                DatagramPacket packet = new DatagramPacket(container,0,container.length);

                // receive
                socket.receive(packet);


                byte[] data = packet.getData();
                String receiveData = new String(data);
                System.out.println(Thread.currentThread().getName() + ":" + receiveData);


                if (receiveData.equals("bye")){
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        socket.close();
    }
}
  • Teacher side
package github.Web.Demo04;

/**
 * @author subeiLY
 * @create 2021-06-11 18:23
 */
public class StudentClient {
    public static void main(String[] args) {
        new Thread(new TalkSend(7777,"localhost",8900)).start();
        new Thread(new TalkReceive(9999),"teacher").start();

    }
}
  • Student side
package github.Web.Demo04;

/**
 * @author subeiLY
 * @create 2021-06-11 18:23
 */
public class TeacherClient {
    public static void main(String[] args) {
        new Thread(new TalkSend(5555,"localhost",9999)).start();
        new Thread(new TalkReceive(8900),"student").start();

    }
}

8.URL

  • https://www.baidu.com

  • Uniform resource locator: locate a resource on the Internet

  • DNS domain name resolution www.baidu.com com —> xxx. xxx. xxxx. xxx…xxx

agreement:// ip address: port number / project name / resource
package github.Web.Demo05;

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

/**
 * @author subeiLY
 * @create 2021-06-06 15:16
 */
public class URLDemo01 {
    public static void main(String[] args) throws MalformedURLException {

        URL url = new URL("http://localhost:8080/helloworld/insex" +
                ".jsp?username=subeily&password=123");

        System.out.println(url.getProtocol());  // agreement
        System.out.println(url.getHost());  // Host IP
        System.out.println(url.getPort());  // port
        System.out.println(url.getPath());  // route
        System.out.println(url.getFile());  // file name
        System.out.println(url.getQuery()); // parameter

    }
}
  • Download files on Web pages

    • 1. Start tomcat server;
    • 2. Put the files in tomcat;

  • 3. Conduct relevant tests.
package github.Web.Demo05;

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

/**
 * @author subeiLY
 * @create 2021-06-06 15:16
 */
public class URLDemo02 {
    public static void main(String[] args) throws Exception{

        // 1. Download address
        URL url = new URL("http://localhost:8080/subei/hello.html");

        // 2. Connect to this resource HTTP
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        InputStream is = urlConnection.getInputStream();

        FileOutputStream stream = new FileOutputStream(new File("same.txt"));

        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = is.read(bytes)) != -1){
            stream.write(bytes,0,len);
        }

        stream.close();
        is.close();
        urlConnection.disconnect();

    }
}

Topics: Java network