Java learning summary (2021 edition) --- basics of network programming

I. Overview

  • The purpose of network programming: directly or indirectly realize data exchange and communication with other computers through network protocols

  • Two problems need to be solved to realize network communication:

    • How to accurately locate one or more hosts on the network; locate specific applications on the host
    • After finding the hostHow to transfer data reliably and efficiently

Two: Elements of Network Communication

  • Solve the problem one: IP and port number
  • Solve the second problem: Provide network communication protocol: TCP/IP reference model (application layer, transport layer, network layer, physical + data link layer)

Communication element 1: IP and port number

Understanding of IP

  • IP : uniquely identifies the computer (communication entity) on the Internet
  • Use the InetAddress class to represent IP in Java
  • IP classification :
    • Method 1: IPv4 and IPv6
    • Method 2: Public address (used by the World Wide Web) and private address (used by the local area network)
  • Domain name : resolve the domain name to an IP address through a domain name resolution server www.baidu.com www.mi.com www.jd.com
  • Domain name resolution : The domain name is easy to remember. When the domain name of a host is entered when connecting to the network, the domain name server (DNS) is responsible for converting the domain name into an IP address, so as to establish a connection with the host.
  • Local loopback address (hostAddress) : 127.0.0.1 Host name (hostName): localhost
  • There are two ways for hosts on the Internet to express addresses:
    • Region name (hostName): www.baidu.com
    • IP address (hostAddress): 202.108.35.210

The port number:
Insert picture description here

InetAddress class
Insert picture description here

  • The domain name is easy to remember. After entering the domain name of a host when connecting to the network, the domain name server (DNS)
    is responsible for converting the domain name into an IP address, so that the connection can be established with the host. -------DNS

Insert picture description here

  • commonly used ways

Insert picture description here
Code example:

public static void main(String[] args) {
    
    
    try {
    
    
        //通过域名来获得InetAddress实例
        InetAddress inet2 = InetAddress.getByName("www.baidu.com");
        System.out.println(inet2);//www.baidu.com/39.156.66.18
     
        //通过ip来获得InetAddress实例
        InetAddress inet3 = InetAddress.getByName("127.0.0.1");
        System.out.println(inet3);//127.0.0.1
     
        //获取本地InetAddress实例
        InetAddress inet4 = InetAddress.getLocalHost();
        System.out.println(inet4);//DESKTOP-EV2S7MJ/10.1.1.127

        //getHostAddress()获取主机域名
        System.out.println(inet2.getHostName());//www.baidu.com
        //getHostAddress();获取主机的ip地址
        System.out.println(inet2.getHostAddress());//39.156.66.14
    } catch (UnknownHostException e) {
    
    
        e.printStackTrace();
    }
}

Communication element two: network communication protocol

TCP protocol and UDP protocol

Insert picture description here

  • Three-way handshake: ensure that the communication partner is online
  • Four-way handshake: make sure the connection is broken

Socket
Insert picture description here

  • Commonly used constructors of the Socket class:

    • public Socket(InetAddress address,int port) To create a stream socket and connect it to the specified IP address specified port number.
    • public Socket(String host,int port) To create a stream socket and connect it to the designated host specified in the port number.
  • Common methods of the Socket class:

Insert picture description here

Three: TCP network programming

1: Brief description

Socket programming based on the Java language is divided into client and server

2: The working process of the client Socket includes the following four basic steps:

Insert picture description here

  • Note: The client program can use the Socket class to create objects,At the same time created will automatically connect to the server side initiates
    contact

3: The working process of the server program includes the following four basic steps:
Insert picture description here
4: Example:

Insert picture description here

Code example 1: ----- The client sends information to the server, and the server displays the data on the console

import org.junit.Test;

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.util.Objects;

/**
 * 实现TCP的网络编程
 * 例子1:客户端发送信息给服务端,服务端将数据显示在控制台上
 */
public class TCPTest1 {
    
    

    //客户端
    @Test
    public void client()  {
    
    
        Socket socket = null;
        OutputStream os = null;
        try {
    
    
            //1.创建Socket对象,指明服务器端的ip和端口号
            InetAddress inet = InetAddress.getByName("192.168.14.100");//获取此IP地址的主机名
            socket = new Socket(inet,8899);
            //2.获取一个输出流,用于发送数据给服务器
            os = socket.getOutputStream();
            //3.写出数据的操作
            os.write("你好,我是客户端mm".getBytes());
            
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            //4.资源的关闭
            if(os != null){
    
    
                try {
    
    
                    os.close();
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                }

            }
            if(socket != null){
    
    
                try {
    
    
                    socket.close();
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                }

            }
        }



    }
    //服务端
    @Test
    public void server()  {
    
    

        ServerSocket ss = null;
        Socket socket = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
    
    
            //1.创建服务器端的ServerSocket,指明自己的端口号
            ss = new ServerSocket(8899);
            //2.调用accept()表示接收来自于客户端的socket(监听一个客户端的连接)
            //该方法是一个阻塞方法,如果没有客户端连接将一直等待
            socket = ss.accept();
            //3.获取输入流,用来接收客户端发送的数据
            is = socket.getInputStream();

            //不建议这样写,可能会有乱码
//        byte[] buffer = new byte[1024];因为此处长度如果小于接受数据的长度,导致分成两半,后续用String接收会乱码
//        int len;
//        while((len = is.read(buffer)) != -1){
    
    
//            String str = new String(buffer,0,len);
//            System.out.print(str);
//        }
            
            //4.读取输入流中的数据
            //因为此处如果小于接收的数据长度,并不会单独还原成字符串,而是先拼起来整体再还原
            baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[5];
            int len;
            while((len = is.read(buffer)) != -1){
    
    
            	/**ByteArrayOutputStream源码
            	 * public synchronized void write(byte b[], int off, int len) {
        				Objects.checkFromIndexSize(off, len, b.length);
        				ensureCapacity(count + len);
        				System.arraycopy(b, off, buf, count, len);
        				count += len;
    				}
            	 */
            	//把数据写到baos对象,以便后续整体还原
                baos.write(buffer,0,len);
            }
            /**ByteArrayOutputStream源码
             * protected byte buf[];
             */
            
            /**
             * public synchronized String toString() {
        		return new String(buf, 0, count);
    		}
             */
            		//把内部字节字符直接转换成字符串
            System.out.println(baos.toString());

            System.out.println("收到了来自于:" + socket.getInetAddress().getHostAddress() + "的数据");

        } catch (IOException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            if(baos != null){
    
    
                //5.关闭资源
                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(ss != null){
    
    
                try {
    
    
                    ss.close();
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                }
            }

        }





    }

}

Code example 2: ----- Send a file from the client to the server, and the server saves it locally. And return "send successfully" to the client


/*
    这里涉及到的异常,应该使用try-catch-finally处理
     */

public class TCPTest3 {
    
    
    @Test//客户端
    public void client() throws Exception{
    
    
        //创建Socket对象,指明服务器端的ip和端口号
        InetAddress inet = InetAddress.getByName("127.0.0.1");
        Socket socket = new Socket(inet,9090);
      
        //获取输出流,用来发送数据给服务器
        OutputStream so = socket.getOutputStream();
        FileInputStream fis = new FileInputStream(new File("one.jpg"));
        byte[] buffer = new byte[1024];
        int len;
        //将从文件中读取的数据发送给服务器
        while((len = fis.read(buffer)) != -1){
    
    
            so.write(buffer,0,len);
        }
        //关闭数据的输出,会在流末尾写入一个“流的末尾”的标记,服务器才能读到-1,否则对方的读取会一直阻塞
        socket.shutdownOutput();
      
        //接收来自服务器端的数据,并显示到控制台上
        InputStream is = socket.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        System.out.println("我想接收来自服务器的数据");
        while((len = is.read(buffer)) != -1){
    
    
            baos.write(buffer,0,len);
        }
        System.out.println(baos.toString());
        //关闭流
        baos.close();
        is.close();
        fis.close();
        so.close();
        socket.close();
    }

    @Test//服务器
    public void server() throws Exception{
    
    
        ServerSocket ss = new ServerSocket(9090);
        Socket socket = ss.accept();
        InputStream is = socket.getInputStream();
        FileOutputStream fos = new FileOutputStream(new File("three.jpg"));
        byte[] buffer = new byte[1024];
        int len;
        while((len = is.read(buffer)) != -1){
    
    
            fos.write(buffer,0,len);
        }
        //服务器端给与客户端反馈
        OutputStream os = socket.getOutputStream();
        os.write("你好,文件我已经收到".getBytes());
        //关闭流
        os.close();
        fos.close();
        is.close();
        socket.close();
        ss.close();
    }
}

Four: UDP network programming (understand)

Five: URL programming-it represents the address of a certain resource on the Internet

Insert picture description here

Overview:
Insert picture description here
The basic structure of URL consists of 5 parts:
Insert picture description here
Common methods of URL class:

Insert picture description here
Code example:

public class URLTest {
    
    

    public static void main(String[] args) {
    
    

        try {
    
    

            URL url = new URL("http://localhost:8080/examples/beauty.jpg?username=Tom");

//            public String getProtocol(  )     获取该URL的协议名
            System.out.println(url.getProtocol());
//            public String getHost(  )           获取该URL的主机名
            System.out.println(url.getHost());
//            public String getPort(  )            获取该URL的端口号
            System.out.println(url.getPort());
//            public String getPath(  )           获取该URL的文件路径
            System.out.println(url.getPath());
//            public String getFile(  )             获取该URL的文件名
            System.out.println(url.getFile());
//            public String getQuery(   )        获取该URL的查询名
            System.out.println(url.getQuery());




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

    }


}

Guess you like

Origin blog.csdn.net/m0_51755061/article/details/114269658