First knowledge of java network programming

Posted by slshmily on Tue, 28 Dec 2021 16:20:22 +0100

Network programming

1.1 general

Call - connect - answer - call TCP

Send SMS - send it and it's done - receive UDP

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

Purpose of network programming:

Communication, data exchange, communication

What is needed to achieve this effect:

  1. How to accurately locate a host address on the network: 192.168 16.125 port to locate a resource on this computer
  2. After finding the host, how to transmit data?

javaweb: Web programming B/S architecture. Everything is accessed through the browser

Network programming: everything in TCP/IP C/S architecture is accessed through the client

Elements of network communication

How to realize network communication

Address of communication parties: address + port to locate an application on a computer

  • IP LAN public network
  • Port number
  • Example: 192.168 16.124: 5900

Rules: Network Communication Protocol HTTP ftp smtp tcp ucp

TCP/IP Network Model OSI seven layer reference model


Network programming: for TCP UDP

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
  3. Everything is object

cmd find the command line address ping www.baidu.com com
ip address packet

IP

IP address: InetAddress

  • Uniquely locate a computer on the network

  • 127.0. 0.1: local localhost

  • Domain name: memory IP problem

    • IP:
  • ip address classification:

    • Public network (Internet) - private network (LAN)

      • ABCD class IP address


* 192.168.xx,xx is dedicated to the internal use of the organization

  • ipv4

    • == ipv4 == ——127.0. 0.1 consists of 4 bytes. 0 ~ 255 per byte, 4.2 billion (North America 30 Asia 4)
  • ipv6

    • IPV6128 bits, 8 unsigned integers! abcde(16 bits per unsigned integer) can be output

      2001:0bb2:aaaa:0015:0000:0000:1aaa:1312
      

View native IP: ipconfig

code Notes

  • Create package Hide and change the display

  • psvm public static void main() abbreviation

  • surround by try catch

  • ALT+Enter auto prompt

  • sout system.out.println() abbreviation

port

A port represents a process on a computer

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

  • General regulations 0 ~ 65535

  • It is divided into TCP and UDP ports: each has 65535 tcp:80 udp:80 can use 80

    • Under a single protocol, port numbers cannot conflict
  • Port classification

    • Dynamic, private: 49152 ~ 65535

      • netstat -ano; // cmd view all ports
        netstat -ano|findstr "5900";// Find a specified port
        tasklist|findstr "8696" // View processes on a specified port
        
    • Program registration port: 1024 ~ 49151, which is assigned to users or programs

      • Tomcat 8080
      • MySQL 3306
      • Oracle 1521
    • Public ports 0 ~ 1023 (used by built-in processes)

      • http:80 example: www.baidu.com com:80 https:443
      • FTP:21 SSH:22
      • Telent:23

        pid is the process id, not the Port ID

One program and one port;

One port can have multiple processes;

(by the way, a process can have multiple threads (share the system resources of a process to multiple programs in a program, run in parallel, so as to save CPU resources, etc.)

5. Summary:

A network application corresponds to a port;

One port corresponds to one or more processes;

One process corresponds to one or more threads

communication protocol

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

Make things small: layered! TCP / IP (network interconnection protocol) protocol cluster is actually a group of protocols

TCP: user transport protocol UDP: User Datagram Protocol

TCPUDP
Connection, stableNot connected, unstable
Three handshakes (connection), four breakups (disconnection)Whether there is a preparation number or not, it can be sent to you
Client, serverClient, server: there is no clear boundary
The transmission is completed, the connection is released, and the efficiency is lowMissile
DDOS: flood attack! Saturation attack

Handshake: at least three times to ensure a stable connection!

  • A: What are you looking at?
  • B: What do you think?
  • A: Do it!

break up:

  • A: I want to disconnect!
  • B: I know you're disconnecting?
  • B: Are you really disconnected?
  • A: I'm really going to disconnect!

TCP

client

  1. Connect to the server Socket

  2. send message

    package com.kuang.lesson02;
    
    import java.io.IOException;
    import java.io.OutputStream;
    import java.net.InetAddress;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    public class TcpClientDemo01 {
        public static void main(String[] args) {
            Socket socket=null;
            OutputStream os = null;
            try {
                // 1. Know the address of the server
                InetAddress serverIP = InetAddress.getByName("127.0.0.1");
                // 2. There must be a port number
                int port=9999;
                // 3. Create a socket connection
                socket = new Socket(serverIP,port);
                // 4. Send message IO stream
                os = socket.getOutputStream(); // Output stream
                os.write("Hello".getBytes());//In Java, the getBytes() method of String is to get a byte array in the default encoding format of the operating system
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if(os!=null){
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(socket!=null){
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    

The server

  1. Establish service port SeverSocket

  2. Wait for the user's link accept listening

  3. Receive messages from users

    package com.kuang.lesson02;
    
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.InetAddress;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.nio.charset.StandardCharsets;
    
    public class TcpServerDemo01 {
        public static void main(String[] args) {
            ServerSocket serverSocket = null;
            Socket socket = null;
            InputStream is = null;
            ByteArrayOutputStream baos = null;
            try {
                // 1. I have to have a server address
                serverSocket = new ServerSocket(9999);
                // 2. Wait for the client to connect
                socket = serverSocket.accept(); //Equal to the socket of the sender
                // 3. Read the message from the client
                is = socket.getInputStream();
                // There is pipe flow under normal conditions
                /*
                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 array
                byte[] buffer = new byte[1024];
                int len;
                while((len=is.read(buffer))!=-1){
                    baos.write(buffer,0,len);
                }
                System.out.println(baos.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                // To close the flow, close the resource in 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();
                    }
                }
            }
        }
    }
    // Normal items handle exceptions first to ensure that the code can run normally
    

    Join while(true) to listen all the time

    while(true){
                   // 1. I have to have a server address
                serverSocket = new ServerSocket(9999);
                // 2. Wait for the client to connect
                socket = serverSocket.accept(); //Equal to the socket of the sender
                baos = new ByteArrayOutputStream(); // Byte array
                byte[] buffer = new byte[1024];
                int len;
                while((len=is.read(buffer))!=-1){
                    baos.write(buffer,0,len);
                }
                System.out.println(baos.toString());
    }
    

File upload

Turn the file into a stream, and then output the file

Make sure that the server has received the completion before disconnecting

The pipeline flow of the file is used when the file is accepted

Accept characters and use the pipeline flow of characters

Tomcat

C/S end B/S end

Server

  • Custom S
  • Tomcat server S: Java background development

client

  • Custom C
  • Browser B

logging.properties configure the default GBK of the window

UDP

Send text messages without connecting. You need to know the other party's address

Two classes: class DatagramPacket; class DatagramSocket

send message

package com.kuang.lesson03;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;

//No connection to the server is required
public class UdpClientDemo01 {
    //1. Create a Socket
    public static void main(String[] args) throws Exception {
        DatagramSocket socket=new DatagramSocket();
        //2. Create a package
        // To whom
        InetAddress localhoost = InetAddress.getByName("localhost");
        int port=9090;
        String msg="hello world";
        // Data, starting from the length of the data, to whom,
        DatagramPacket packet = new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,localhoost,port);

        //3. Send packet
        socket.send(packet);
        //4. Close the flow
        socket.close();
    }


}

Receiving message - receiving end

package com.kuang.lesson03;

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

// Or wait for the connection of the client, just don't inform you to listen at any time, not the server
public class UdpServerDemo01 {
    public static void main(String[] args) throws Exception {
        // Server side open port
        DatagramSocket socket = new DatagramSocket(9090);
        // Receive packet
        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer,buffer.length);

        socket.receive(packet); // Blocking receive alive
        System.out.println(packet.getAddress().getHostAddress());
        System.out.println(new String(packet.getData(),0,packet.getLength()));
        // Close connection
        socket.close();
    }
}

Circular transmission

Sender

package com.kuang.chat;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.*;

public class UdpSenderDemo01 {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(8888);
//        InetAddress localhoost = InetAddress.getByName("localhost");
        // packet preparation data: the console reads system in
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        while (true){
            String data=reader.readLine();
            //Convert data
            byte[] datas = data.getBytes(); //Specific data

            DatagramPacket packet = new DatagramPacket(datas,
                    0, datas.length, new InetSocketAddress("localhost",6666));
            // Change InetSocketAddress("localhost") in class to InetSocketAddress("localhost",6666));

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

        socket.close();
    }
}

receiver

package com.kuang.chat;

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

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

        // Loop receiving while (true)
        while (true){
            // Ready to receive package
            byte[] container = new byte[1024];
            DatagramPacket packet = new DatagramPacket(container,0,container.length);
            socket.receive(packet); // Blocking receiving package

            // Read the package, but also make a judgment of disconnection
            // Disconnect bye means to disconnect
            byte[] data = packet.getData();
            String receiveData = new String(data, 0, packet.getLength()); // Change the data and length in class to packet length
            System.out.println(receiveData);

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

        }
        socket.close();
    }
}

The next step is online consultation

Online consultation: both can be the sender and the receiver

alt+insert complement constructor

ctrl+alt+T complement throw


cd... /... / return multiple

Package name compilation

package com.kuang.chat;

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;

    //  Open connection
    public TalkSend(int fromPort, String toIP, int toPort) {
        this.fromPort = fromPort;
        this.toIP = toIP;
        this.toPort = toPort;

        try {
           socket = new DatagramSocket(fromPort);
            //        InetAddress localhoost = InetAddress.getByName("localhost");
            // packet preparation data: the console reads system in
            reader = new BufferedReader(new InputStreamReader(System.in));
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {

        while (true){
            try {           // Why did you throw an exception??
                String data = reader.readLine();
                //Convert data
                byte[] datas = data.getBytes(); //Specific data

                DatagramPacket packet = new DatagramPacket(datas,
                        0, datas.length, new InetSocketAddress(this.toIP,this.toPort));
                // Change InetSocketAddress("localhost") in class to InetSocketAddress("localhost",6666));

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

        }
        socket.close();
    }
}

package com.kuang.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 msgFrom) {
        this.port = port;
        this.msgFrom=msgFrom;
        try {
            socket = new DatagramSocket(port);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        // Loop receiving while (true)
        while (true){

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

                // Read the package, but also make a judgment of disconnection
                // Disconnect bye means to disconnect
                byte[] data = packet.getData();
                String receiveData = new String(data, 0, packet.getLength()); // Change the data and length in class to packet length
                System.out.println(msgFrom+":"+receiveData);

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

package com.kuang.chat;

//end
public class TalkStudent {
    public static void main(String[] args) {
        // Open two threads
        new Thread(new TalkSend(7777,"localhost",9999)).start();
        new Thread(new TalkReceive(8888,"teacher")).start();
    }
}

package com.kuang.chat;

public class TalkTeacher {
    public static void main(String[] args) {
        // The static proxy mode proxy is the runnable interface
        new Thread(new TalkSend(5555,"localhost",8888)).start();
        new Thread(new TalkReceive(9999,"student")).start();
    }
}

URL

Uniform resource locator: used to locate a resource on the Internet

The first is the agreement

DNS domain name resolution should put www.baidu Com parses into a XXX One IP of x... x... x

URL Composition - agreement:// IP address: port number (connected) / project name / resource

ge com.kuang.chat;

//End
public class TalkStudent {
public static void main(String[] args) {
//Open two threads
new Thread(new TalkSend(7777,"localhost",9999)).start();
new Thread(new TalkReceive(8888, "teacher")) start();
}
}

```java
package com.kuang.chat;

public class TalkTeacher {
    public static void main(String[] args) {
        // The static proxy mode proxy is the runnable interface
        new Thread(new TalkSend(5555,"localhost",8888)).start();
        new Thread(new TalkReceive(9999,"student")).start();
    }
}

URL

Uniform resource locator: used to locate a resource on the Internet

The first is the agreement

DNS domain name resolution should put www.baidu Com parses into a XXX One IP of x... x... x

URL Composition - agreement:// IP address: port number (connected) / project name / resource

Topics: Java socket