Java network programming

summary

  • Call – connect – receive – call TCP
  • Send SMS – send and finish – receive UDP
  • Purpose of network programming:
    • Dissemination and exchange of information, data exchange and communication
  • Premise:
    • How to accurately locate a host 192.168.16.124: port on the network and locate a resource on this computer
    • How do I transfer data when I find this host?
  • Network programming: TCP/IP, Java Web page programming: B/S

Elements of network communication

  • Address of both parties:
    • ip
    • Port number
    • 192.168.16.124:5900
  • Rules: protocol of network communication
    • UDP: user transport protocol
    • TCP: User Datagram Protocol
  • TCP/IP four layer conceptual model:
    • application layer
    • Transport layer
    • network layer
    • data link layer
  • 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
  • Everything is object

IP(InetAddress)

  • Uniquely locate a computer on a network
  • 127.0.0.1: local localhost
  • Classification of IP addresses
    • ipv4/ipv6
      • IPV4, composed of 4 bytes, 4.2 billion in total; 3 billion in North America and 400 million in Asia; It was exhausted in 2011
      • IPV6128 bits, 8 unsigned integers!
      • 2001:5a42:2451:abcc:1ccc:1342
    • Public network (Internet) - private network (LAN)
      • ABCD class address
      • 192.168.xx.xx, for internal use of the organization
  • Domain name: memory IP problem
package ink.lesson01;

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

            InetAddress inetAddress3 = InetAddress.getByName("localhost");
            System.out.println(inetAddress3);   // localhost/127.0.0.1

            InetAddress inetAddress4 = InetAddress.getLocalHost();
            System.out.println(inetAddress4);   // DC-Pro/10.200.34.15


            //Query website ip address
            InetAddress inetAddress2 = InetAddress.getByName("www.baidu.com");
            System.out.println(inetAddress2);   // www.baidu.com/14.215.177.38
            
            System.out.println("\n====================\n");

            //common method
            System.out.println(inetAddress2.getAddress());      // [B@14ae5a5
            System.out.println(inetAddress2.getCanonicalHostName());        // 14.215.177.38
            System.out.println(inetAddress2.getHostAddress());      // 14.215.177.38
            System.out.println(inetAddress2.getHostName());     // www.baidu.com

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

port

  • A port represents the progress of a program on a computer

    • Different processes have different port numbers to distinguish software!
    • Regulation: 0 ~ 65535
    • TCP and UDP: 65535 * 2 in total. Under a single protocol, the port numbers cannot conflict
  • Port classification:

    • Total ports 0 ~ 1023

      • HTTP: 80
      • HTTPS: 443
      • FTP: 21
      • Telent: 23
    • Program registration port: 1024 ~ 49151, assign users or programs

      • Tomcat: 8080
      • MySQL: 3306
      • Oracle: 1521
    • Dynamic and private: 49152 ~ 65535

      • netstat -ano	#View all ports
        netstat -ano|findstr "5900"		#View the specified port
        

communication protocol

  • Agreement: agreement, just as we communicate in Mandarin

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

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

  • 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?
        C: 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, server

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

    • udp: send SMS

      • Not connected, unstable
      • There is no clear boundary between client and server
      • Whether you are ready or not, you can send a message to you~
      • DDOS: flood attack

TCP

  • client
    • Connect to the server Socket
    • send message
package ink.lesson02;

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

//client
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("Hello, this is a TCP Chat model".getBytes());

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //Resources need to be closed after use. Pay attention to the order
            //In the development of regular projects, it is necessary to catch exceptions. The shortcut key of IDEA is Ctrl + Alt + T
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
  • Server
    • Establish service port ServerSocket
    • Wait for the user's connection accept
    • Receive user messages
package ink.lesson02;

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

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

            //Loop, continuously receiving messages
            while (true) {
                //2. Wait for the client to connect
                socket = serverSocket.accept();
                //3. Read the message from 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 (Exception e) {
            e.printStackTrace();
        } finally {
            //Resources need to be closed after use. Pay attention to the order
            //In the development of regular projects, it is necessary to catch exceptions. The shortcut key of IDEA is Ctrl + Alt + T
            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

  • Note the path of the file. The path folder must be created in advance
  • Server
package ink.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. Create service
        ServerSocket serverSocket = new ServerSocket(9999);
        //2. Listen to the connection of the client
        Socket socket = serverSocket.accept();  //Blocking listening will wait for the client to connect
        //3. Get input stream
        InputStream is = socket.getInputStream();

        //4. Document output
        FileOutputStream fos = new FileOutputStream(new File("Network programming/src/newfile/new-kb.png"));
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) != -1) {
            fos.write(buffer,0,len);
        }

        //Notify the client that I have received it
        OutputStream os = socket.getOutputStream();
        os.write("I've received it. You can disconnect it".getBytes());

        //close resource
        fos.close();
        is.close();
        socket.close();
        serverSocket.close();
    }
}
  • client
package ink.lesson02;

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

public class TcpClientDemo02 {
    public static void main(String[] args) throws Exception {
        //1. Create a Socket connection
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9999);
        //2. Create an output stream
        OutputStream os = socket.getOutputStream();

        //3. Read the file
        FileInputStream fis = new FileInputStream(new File("Network programming/src/file/kb.png"));
        //4. Write out documents
        byte[] buffer = new byte[1024];
        int len;
        while ((len = fis.read(buffer)) != -1) {
            os.write(buffer,0,len);
        }

        //Inform the service, please. I'm finished
        socket.shutdownInput();     //I've transmitted it!

        //Make sure that the server has received it before you can disconnect
        InputStream inputStream = socket.getInputStream();
        //String byte[]
        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();
        fis.close();
        os.close();
        socket.close();
    }
}

Tomcat

  • Server

    • Custom S
    • Tomcat server S: Java background development
  • client

    • Custom C
    • Browser B
  • Random cat character problem:

    • Open \ apache-tomcat-8.5.64 \ conf \ logging properties
    • Modify UTF-8 to GBK: Java util. logging. ConsoleHandler. encoding = GBK

UDP

  • Send message: do not connect, but you need to know the other party's address
  • send message
package ink.lesson03;

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

//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();
    }
}
  • receiving end
package ink.lesson03;

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

//Wait for the client to connect!
public class UdpServerDemo01 {
    public static void main(String[] args) throws Exception {
        //Open port
        DatagramSocket socket = new DatagramSocket(9090);

        //Receive packet
        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);

        socket.receive(packet);     //Blocking reception

        System.out.println(packet.getAddress().getHostAddress());   // 127.0.0.1
        System.out.println(new String(packet.getData(),0,packet.getLength()));  // Hello, server

        //Close connection
        socket.close();
    }
}

Loop sending and receiving messages

  • send message
package ink.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);

        //Prepare data: the console reads 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();
    }
}
  • receive messages
package ink.chat;

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

public class UdpReceiveDemo01 {
    public static void main(String[] args) throws Exception {
        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);     //Blocking receiving package

            //Disconnect bye
            byte[] data = packet.getData();
            String receiveData = new String(data,0, data.length);

            System.out.println(receiveData);

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

        socket.close();
    }
}

Online consultation

  • Both can be sender or receiver (multithreading)
package ink.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;

    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 (SocketException e) {
            e.printStackTrace();    //Print stack information
        }
    }

    @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 (IOException e) {
                e.printStackTrace();
            }
        }

        socket.close();
    }
}
package ink.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 (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {

        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

                //Disconnect 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 ink.chat;

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 ink.chat;

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

URL

https://www.baidu.com/

Uniform resource locator: to locate a resource on the Internet

DNS domain name resolution: resolve the domain name to an IP address

agreement://ip address: port / project name / resource
  • URL class in Java
package ink.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=kuangshen&password=123");
        System.out.println(url.getProtocol());  //Protocol name
        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

        /*
            http
            localhost
            8080
            /helloworld/index.jsp
            /helloworld/index.jsp?username=kuangshen&password=123
            username=kuangshen&password=123
         */
    }
}
  • Download resources on the network
package ink.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. Download address
        URL url = new URL("http://127.0.0.1:8080/alibaba/hello.txt");

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

        InputStream inputStream = urlConnection.getInputStream();

        FileOutputStream fos = new FileOutputStream("Network programming/src/newfile/hello.txt");

        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) != -1) {
            fos.write(buffer,0,len);    //Write this data
        }

        fos.close();
        inputStream.close();
        urlConnection.disconnect();     //Disconnect
    }
}

Added by DaiLaughing on Sat, 19 Feb 2022 13:29:08 +0200