JAVA study notes—network programming

1. Concept

TCP: Need confirmation from the other party to establish connection

UDP: Just send it, don’t worry about the other party

1.1 Computer Network

Computer network refers to connecting multiple computers and their external devices with independent functions in different geographical locations through communication lines. With the management and assistance of network operating systems, network management software and network communication protocols , resource sharing and Computer systems for information transfer.

1.2 Purpose of network programming

For example: radio station (broadcasting information) data exchange

1.3 What is needed to achieve this effect?

How to locate a host on the network?

  • The IP address and port number of the host (locating a resource on the host)

    How to transfer data after finding this host?

  • JavaWeb: web programming (B/S)

  • Network programming: TCP/IP (C/S)

2. Network communication elements

How to achieve network communication?

  • Addresses of both parties communicating: IP address and port number
  • Rules: Protocol for network communication (TCP/IP reference model)

OSI seven-layer network model

TCP/IP four-layer conceptual model

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 an object (IP class, TCP class)

3. IP

API corresponding to the ip address: InetAddress

  • Uniquely locate a network computer
  • 127.0.0.1: localhost

Classification of IP addresses:

  • Sort by IP address
    • ipv4: For example, 127.0.0.1, consists of four bytes, each byte has a length of 0-255 (4.2 billion, all used up in 2011)
    • ipv6: For example 240e:33d:2f9a:6600:948c:bd86:7d89:e527, there are eight unsigned integers to represent 128 bits
  • According to the public network-private network classification (campus network belongs to private network)
    • ABCD class address
    • 192.168.xx.xx is exclusively for internal use of the organization (LAN)
    • Private network is also called LAN

Reasons for the birth of the domain name:

  • Solve the problem of memory IP address
//测试IP
public class TestInetAddress {
    
    
    public static void main(String[] args) {
    
    
        try {
    
    
            //查询本机地址
            InetAddress inetAddress1 = InetAddress.getByName("127.0.0.1");
            InetAddress inetAddress3 = InetAddress.getByName("localhost");
            InetAddress inetAddress4 = InetAddress.getLocalHost();
            //查询网站ip地址
            InetAddress inetAddress2 = InetAddress.getByName("www.baidu.com");
            //常用方法
            System.out.println(inetAddress2.getAddress());
            System.out.println(inetAddress2.getCanonicalHostName());//规范的名字
            System.out.println(inetAddress2.getHostAddress());//ip
            System.out.println(inetAddress2.getHostName());//域名:或者自己电脑的名字

            System.out.println(inetAddress1);
            System.out.println(inetAddress2);
            System.out.println(inetAddress3);
            System.out.println(inetAddress4);
        } catch (UnknownHostException e) {
    
    
            throw new RuntimeException(e);
        }
    }
}

4. Port

A port represents the process of a program on a computer

  • Different processes have different port numbers to distinguish software
  • A program that is specified to run on a computer: 0-65535
  • Each protocol can run this amount (TCP, UDP: 65535*2)
  • Programs of different protocols can have the same port number, but programs of the same protocol cannot have the same port number, otherwise there will be a conflict!

Port classification:

  • Public port 0-1023
  • HTTP:80
  • HTTPS:443
  • FTP:21
  • Talent:23

Program registration port 1024-49151 (used to assign to users and programs)

  • Tomcat:8080
  • MySQL:3306
  • Oracle:1521

Dynamic, private port 49152-65535

//查看所有程序进程端口
netstat -ano

//查看某个具体的端口(用来检测哪个端口冲突)
netstat -ano|findstr "3306"

//查看指定端口的进程
tasklist|findstr "8696"

What is the difference between PID and port number?

  • A port number is a unique identifier assigned to each process by the system
  • pid is the identity of each process. As soon as the program is run, the system will automatically assign a unique pid to the process. After the process is terminated, the pid is recycled by the system and may continue to be assigned to newly running programs;

Configure the mapping address of this machine: (What is it used for?)

​ When accessing a website on the Internet, we must first resolve the network domain name (similar to www.xx.com) into an IP address through a DNS domain name server before our computer can access it. If we have to wait for the domain name server to resolve and return IP information for each domain name request, the efficiency of accessing the network will be reduced, and the Hosts file can improve the resolution efficiency. According to Windows system regulations, before making a DNS request, the Windows system will first check whether there is such an address mapping relationship in its Hosts file. If so, it will call the IP address mapping. If not, it will propose domain name resolution to a known DNS server. In other words, the request level of Hosts is higher than that of DNS.

5. Communication protocol

Agreement: Agreement, just like the Mandarin we speak at work

Network communication protocol: transmission rate…

​ TCP/IP protocol cluster: It is the foundation of the Internet and the most popular networking form today. TCP/IP is synonymous with a group of protocols, including many other protocols, forming the TCP/IP protocol suite. The more important ones include SLIP protocol, PPP protocol, IP protocol, ICMP protocol, ARP protocol, TCP protocol, UDP protocol, FTP protocol, DNS protocol, SMTP protocol, etc.

Several important agreements:

  • TCP: User Transport Protocol
  • UDP: User Datagram Protocol

Notable protocols:

  • TCP
  • IP: Internet Protocol

Comparison between TCP and UDP:

TCP: make a phone call

  • connection, stability
  • Three handshakes and four waves
三次握手(最少需要三次来保证稳定连接)
A:你瞅啥!
B:瞅你咋地!
A:干一场!

四次挥手
A:我要走了
B:你真的要走了吗
B:你真的真的要走了吗
A:我真的要走了

  • client, server
  • Establish a connection, complete the transmission, release the connection, low efficiency

UDP: Send SMS

  • No connection required, unstable
  • Client, server (the boundary is not very clear)
  • The "missile" has a clear target, regardless of whether the opponent is ready to release it
  • DDOS flood attack (spam text messages block the line)

6. TCP

Call: connection established - transfer completed - connection destroyed

6.1 TCP protocol workflow

  1. client
    • Connect to server Socket
    • Send a message
//客户端
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");
            //2. 端口号
            int port = 9999;
            //3. 创建一个socket 连接
            socket = new Socket(serverIP,port);
            //4. 发生消息 IO流
            os = socket.getOutputStream();
            os.write("你好,世界".getBytes());
        } catch (IOException e) {
    
    
            throw new RuntimeException(e);
        } finally {
    
    
            if(socket!=null){
    
    
                try {
    
    
                    socket.close();
                } catch (IOException e) {
    
    
                    throw new RuntimeException(e);
                }
            }
            if(os!=null){
    
    
                try {
    
    
                    os.close();
                } catch (IOException e) {
    
    
                    throw new RuntimeException(e);
                }
            }
        }

    }
}

Server

  • Create server port ServerSocket
  • Waiting for the user's connection accept()
  • Receive user messages
//服务端
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);
            while(true){
    
    
                //2. 等待客户端连接过来
                socket = serverSocket.accept();
                //3. 读取客户端的消息
                is = socket.getInputStream();
                //管道流 字符流
                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());
            }
            /*
            byte[] buffer = new byte[1024];
            int len;
            while((len=is.read(buffer))!=-1){
                String msg = new String(buffer,0,len);
                System.out.println(msg);
            }
            */

        } catch (IOException e) {
    
    
            throw new RuntimeException(e);
        } finally {
    
    
            //关闭资源
            if(baos!=null){
    
    
                try {
    
    
                    baos.close();
                } catch (IOException e) {
    
    
                    throw new RuntimeException(e);
                }
            }
            if(is!=null){
    
    
                try {
    
    
                    is.close();
                } catch (IOException e) {
    
    
                    throw new RuntimeException(e);
                }
            }
            if(socket!=null){
    
    
                try {
    
    
                    socket.close();
                } catch (IOException e) {
    
    
                    throw new RuntimeException(e);
                }
            }
            if(serverSocket!=null){
    
    
                try {
    
    
                    serverSocket.close();
                } catch (IOException e) {
    
    
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

First start the server to listen to receive the message, then the client sends the message according to the corresponding address, and the server will respond as soon as it receives the connection.

6.2 File upload

Service-Terminal

public class TcpServerDemo02 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        //1. 创建服务
        ServerSocket serverSocket = new ServerSocket(9000);
        //2. 监听客户端连接
        Socket socket = serverSocket.accept();//阻塞式监听,会一直等待客户端连接
        //3. 获取输入流
        InputStream is = socket.getInputStream();
        //4. 文件输出
        FileOutputStream fos = new FileOutputStream(new File("/Users/xay/Desktop/编程/JAVA-FullStack/JavaSE/receive.jpg"));
        byte[] bytes = new byte[1024];
        int len;
        while((len=is.read(bytes))!=-1){
    
    
            fos.write(bytes,0,len);
        }
        //通知客户端接受完毕
        OutputStream os = socket.getOutputStream();
        os.write("文件接受完毕,可以断开连接".getBytes());
        //5. 关闭资源
        os.close();
        fos.close();;
        is.close();
        socket.close();
        serverSocket.close();
    }
}

client

public class TcpClientDemo02 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        //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("/Users/xay/Desktop/编程/JAVA-FullStack/JavaSE/baidu1.jpg"));
        //4. 写出文件
        byte[] bytes = new byte[1024];
        int len;
        while((len = fis.read(bytes))!=-1){
    
    
            os.write(bytes,0,len);
        }
        //通知服务器,我已经结束
        socket.shutdownOutput();//我已传输完成

        //确定服务器接收完毕,才能断开连接
        InputStream inputStream = socket.getInputStream();
        //String byte[];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] bytes2 = new byte[1024];
        int len2;
        while((len2 = inputStream.read(bytes2))!=-1){
    
    
            baos.write(bytes2,0,len2);
        }
        System.out.println(baos.toString());
        //5. 关闭
        baos.close();
        inputStream.close();
        fis.close();
        os.close();
        socket.close();
    }
}

7. Tomcat

  1. client
    • Client custom C
    • Browser C
  2. Server
    • Server-side customization S
    • Tomcat S

Replenish:

  • .bat is an executable file under Windows system
  • .sh is an executable file under Linux system

8. UDP

8.1 UDP sending messages

Send SMS: No need to connect, just need to know the other party’s address!

  1. Sender (can be client or server)
//不需要连接服务器
public class UdpClientDemo01 {
    
    
    public static void main(String[] args) throws Exception {
    
    
        //1. 建立一个Socket
        DatagramSocket socket = new DatagramSocket();
        //2. 建个包
        //发生给谁
        InetAddress localhost = InetAddress.getByName("localhost");
        int port = 9090;
        //数据,数据长度起始,结束,要发送给谁
        String msg = "你好,服务器!";
        DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, localhost, port);
        //3. 发送包
        socket.send(packet);
        //4. 关闭流
        socket.close();
    }
}
  1. Receiver (can be a client or a server)
//服务器端,开放端口,还是要等待客户端的连接
public class UdpServerDemo01 {
    
    
    public static void main(String[] args) throws IOException {
    
    
        //开放端口
        DatagramSocket socket = new DatagramSocket(9090);
        //接受数据包
        byte[] bytes = new byte[1024];
        DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);//接收
        socket.receive(packet);//阻塞接收
        System.out.println(packet.getAddress().getHostAddress());
        System.out.println(new String(packet.getData(),0,packet.getLength()));
        //关闭连接
        socket.close();
    }
}

8.2. Consultation

sending end

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

Receiving end

public class UdpReceiveDemo02 {
    
    
    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();
    }
}

8.3. UDP realizes multi-threaded online consultation

sending end

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

    @Override
    public void run() {
    
    
        while (true) {
    
    
            String data = null;
            try {
    
    
                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 (Exception e) {
    
    
                e.printStackTrace();
            }

        }
        socket.close();
    }
}

Receiving end

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() {
    
    
        while (true) {
    
    
            try {
    
    
                //准备接受包裹
                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(msgFrom + ":" + receiveData);
                if (receiveData.equals("bye")) {
    
    
                    break;
                }
            } catch (IOException e) {
    
    
                throw new RuntimeException(e);
            }
        }
        socket.close();
    }
}

student

public class TalkStudent {
    
    
    public static void main(String[] args) {
    
    
        //开启两个线程
        new Thread(new TalkSend(7777,"localhost",9999)).start();
        new Thread(new TalkReceive(8888,"老师")).start();
    }
}

teacher

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

9. URL

https://www.baidu.com/

URL: Uniform Resource Locator, used to locate resources on the Internet.

DNS domain name resolver: resolves the domain name (www.baidu.com) into the IP address xxx.xxx

composition:

协议://IP地址:端口号/项目/资源名

Example:

public class URLDemo01 {
    
    
    public static void main(String[] args) throws MalformedURLException {
    
    
        URL url = new URL("http://localhost:8080/helloworld/index.jsp?username=xay&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());//参数
    }
}

Download resources via URL

public class URLDown {
    
    
    public static void main(String[] args) throws IOException {
    
    
        //1. 下载地址
        URL url = new URL("https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png");
        //2. 连接到这个资源 HTTP
        HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();

        InputStream is = urlConnection.getInputStream();
        FileOutputStream fos = new FileOutputStream("/Users/xay/Desktop/编程/JAVA-FullStack/JavaSE/JavaBasics/src/com/net/demo04/test.png");
        byte[] bytes = new byte[1024];
        int len;
        while((len=is.read(bytes))!=-1){
    
    
            fos.write(bytes,0,len);//写出这个注释
        }
        fos.close();
        is.close();
        urlConnection.disconnect();//断开连接

    }
}

music download

public class MusicDownload {
    
    
    public static void main(String[] args) throws IOException {
    
    
        URL url = new URL("https://m701.music.126.net/20230201161620/fbc4a9b932035588e92df9f6a2f27a3f/jdyyaac/obj/w5rDlsOJwrLDjj7CmsOj/14096431555/252f/b246/4da5/88c4d262ef5e22cb2a24b7c35922913b.m4a");
        HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
        InputStream is = urlConnection.getInputStream();
        FileOutputStream fos = new FileOutputStream("/Users/xay/Desktop/编程/JAVA-FullStack/JavaSE/JavaBasics/src/com/net/demo04/abc.m4a");
        byte[] bytes = new byte[1024];
        int len;
        while((len=is.read(bytes))!=-1){
    
    
            fos.write(bytes,0,len);
        }
        System.out.println("音乐下载完毕");
        fos.close();
        is.close();
        urlConnection.disconnect();
    }
}

Guess you like

Origin blog.csdn.net/weixin_42823298/article/details/128893169