java network programming

Network programming

1.1 general

Computer network:

Computer network refers to connecting multiple computers and their external devices with independent functions in different geographical locations through communication lines
Operating system, network management software and network communication protocol A computer system that realizes resource sharing and information transmission under the management and coordination of.

Purpose of network programming:

Radio stations... Transmit and exchange information and data. signal 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 this computer
  2. After finding the host, how to transmit data?

javaweb: Web programming B/S
Network programming: TCP/P C/S

1.2 network communication elements

How to realize network communication?
Address of both parties:
●ip
● port number
●192.168.16,124:5900
Rules: protocol of network communication

TCP/IP reference model

Summary:

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

1.3 IP address

The IP address is in the JavaInetAddress class

  • Uniquely locate a computer on a network

  • Native 127.0.0.1: localhost

  • Classification of IP addresses

    • IPV4/ IPV6 protocol

      Pv4 127.0.0.1, composed of 4 bytes, 0 ~ 255, 4.2 billion ~; 3 billion in North America and 400 million in Asia. Exhausted in 2011

      IPv6 2001:3CA1:010F:001A:121B:0000:0000:0010 128 bits. 8 unsigned integers

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

    • 192.168.xx.xx is generally a local area network for internal use in the organization
    • ABCD class address (the following address is IPv4 address)
  • Domain name: memory IP problem!

    • IP: www.vip.com
package com.kuang.ip;

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

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
            InetAddress inetAddress4 = InetAddress.getByName("www.baidu.com");
            System.out.println(inetAddress4);

            //common method
            System.out.println(inetAddress4.getAddress());
            System.out.println(inetAddress4.getCanonicalHostName());//Canonical name
            System.out.println(inetAddress4.getHostAddress());//ip
            System.out.println(inetAddress4.getHostName());//Domain name, or the name of your own computer

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

Operation results

/127.0.0.1
localhost/127.0.0.1
LAPTOP-0SJUQ8J4/192.168.56.1
www.baidu.com/61.135.185.32
[B@4554617c
61.135.185.32
61.135.185.32
www.baidu.com

1.4 ports

  • A port represents the process of a program on a computer:

  • Different processes have different port numbers. Port numbers cannot conflict! Used to distinguish software

  • It is generally specified as 0 ~ 65535

  • TCP and UDP have 65535 ports for each protocol, so there are 65535 * 2 ports in total. Port numbers cannot conflict under a single protocol

  • Port classification

    • Public port 0 ~ 1023

      HTTP: 80
      HTTPS: 443
      FTP: 21
      Telent: 23

  • Program registration port: 1014 ~ 49151, which is assigned to users or programs

    Tomcat: 8080
    MySQL: 3306
    Oracle: 1521

  • Dynamic and private ports: 49152 ~ 65535

    netstat -ano #View all ports
    netstat -ano|findstr "5900" #View the specified port
    tasklist|findstr "8696" #View the process of the specified port
    
    
    package com.kuang.ip;
    
    import java.net.InetSocketAddress;
    
    public class TestInetSocketAddress {
        public static void main(String[] args) {
    
            InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 8080);
            System.out.println(inetSocketAddress);
    
            System.out.println(inetSocketAddress.getAddress());
            System.out.println(inetSocketAddress.getHostName());//address
            System.out.println(inetSocketAddress.getPort());//port
    
        }
    }
    
    

    Operation results

    /127.0.0.1:8080
    /127.0.0.1
    eureka7001.com
    8080
    

1.5 communication protocol (TCP/IP)

Agreement: agreement, just as we speak Mandarin now

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

Question: very complicated—— Make big things small: layered!

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

Important:

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

Famous agreement:

  • TCP: user transport protocol

  • IP: network interconnection protocol

Comparison of TCP and UDP

**TCP: phone**

- Connection, stable
- Three handshakes and four waves
A: What are you looking at?

B: What do you think?

A: Do it!

A: I am afraid that l have to go!

B: Are you really leaving?

B: Are you really leaving?

A: I really have to go!

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

UDP: send SMS

  • Not connected, unstable
  • Client and server: there is no clear boundary
  • Ready or not, it can be sent to you
  • Missile
  • DDOS: flood attack! (saturation attack)

1.6 TCP chat

TCP

client

Connect to the server Socket
send message

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

public class TcpClientDemo01 {
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream os = null;
        try {
            //1. Know the address and port number of the server
            InetAddress serverIP = InetAddress.getByName("127.0.0.1");
            int port = 9999;
            //2. Create a socket connection
             socket = new Socket(serverIP,port);
            //3. Send message IO stream
             os = socket.getOutputStream();
            os.write("Carefree drunkenness".getBytes());

        } catch (Exception 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

The server

Establish service port ServerSocket
Wait for user's link accept
Receive messages from users

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. I want to have an address
             serverSocket = new ServerSocket(9999);
            //2. Wait for the client to connect
             socket = serverSocket.accept();
            //3. Read the information of the client
             is = socket.getInputStream();
            //Pipe flow
             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();
                }
            }
        }
    }
}

File upload

client

import sun.nio.cs.ext.ISCII91;
import sun.security.util.Length;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class TcpClientDemo02 {
    public static void main(String[] args) throws Exception {
        //1. Create socket 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 files = new FileInputStream(new File("qun.jpg"));
        //4. Write documents
        byte[] buffer = new byte[1024];
        int len;
        while ((len=files.read(buffer))!=-1){
            os.write(buffer,0,len);
        }
        
        //Notify the server that I have sent it
        socket.shutdownOutput();

        //Make sure that the server has accepted it before disconnecting
        InputStream inputStream = socket.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer2 = new byte[1024];
        int len2;
        while ((len2=inputStream.read(buffer2))!=-1){
            baos.write(buffer2,0,len2);
        }
        System.out.println(baos.toString());
        
        //5. Close resources   
        baos.close();
        inputStream.close();
        files.close();
        os.close();
        socket.close();
    }
}

Server

package com.tree.lesson02;
import sun.misc.OSEnvironment;

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

public class TcpServerDemo02 {
    public static void main(String[] args) throws IOException {
        //1. Create service
        ServerSocket serverSocket = new ServerSocket(9000);
        //2. Listen to the connection of the client
        Socket socket = serverSocket.accept();//Blocking listening, waiting for the client to connect
        //3. Get input stream
        InputStream is = socket.getInputStream();
        //4. Document output
        FileOutputStream files = new FileOutputStream(new File("receive.jpg"));
        byte[] buffer = new byte[1024];
        int len;
        while ((len=is.read(buffer))!=-1){
            files.write(buffer,0,len);
        }
        
        OutputStream os = socket.getOutputStream();
        os.write("I'm done. You can disconnect".getBytes());
        
        files.close();
        is.close();
        socket.close();
        serverSocket.close();
    }
}

1.7 UDP

send message

Sender

public class UdpClientDemo01 {
    public static void main(String[] args) throws Exception {
        //1. Establish a socket
        DatagramSocket socket = new DatagramSocket();
        //2. Build a package
        String msg = "be leisurely and carefree";
        InetAddress localhost = InetAddress.getByName("localhost");
        int port = 9090;
        DatagramPacket packet = new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,localhost,port);
        //3. Send packet
        socket.send(packet);
        //Close flow
        socket.close();
    }
}

receiving end

public class UdpServerDemo01 {
    public static void main(String[] args) throws Exception {
        //1. Open port
        DatagramSocket socket = new DatagramSocket(9090);
        //2. Accept packets
        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
        socket.receive(packet);//Blocking reception

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

consulting service

Circular transmission

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

        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 ("bye".equals(data)){
                break;
            }
        }
        socket.close();
    }
}

Cyclic reception

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

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

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

Summary

To send data using UDP protocol, you only need "data to be sent + opposite IP + opposite Port".
To receive data, you only need to set your own Port.

1.8 URL

https://www.baidu.com/

Uniform resource locator: to locate a resource on the Internet

agreement://ip address: port / project name / resource

Method analysis

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

public class URLDemo {
    public static void main(String[] args) throws MalformedURLException {
        URL url = new URL("http://localhost:8080/helloworld/index.jsp?username=kuangshen&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());//file
        System.out.println(url.getFile());//Full path
        System.out.println(url.getQuery());//parameter
    }
}

Operation results

http
localhost
8080
/helloworld/index.jsp
/helloworld/index.jsp?username=kuangshen&password=123
username=kuangshen&password=123

Download network resources through url

public class UrlDownLoad {
    public static void main(String[] args) throws Exception {
        //1. Download address
        URL url = new URL("https://win-web-rc01-sycdn.kuwo.cn/303bdee656bd4a7ae6a0cfa8538f1157/614ad690/resource/n3/60/82/1536711583.mp3");
        //2. Connection
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        InputStream inputStream = urlConnection.getInputStream();
        FileOutputStream outputStream = new FileOutputStream("Carefree.mp3");
        byte[] bytes = new byte[1024];
        int len;
        while ((len=inputStream.read(bytes))!=-1){
            outputStream.write(bytes,0,len);
        }
        outputStream.close();
        inputStream.close();
        urlConnection.disconnect();
    }
}

Keywords: Java network Network Protocol

Added by loveranger on Wed, 09 Feb 2022 23:57:51 +0200