java network programming summary

Overview of network programming

  1. How to realize the communication between hosts in the network

    • Address of both parties
      • IP
      • Port number
    • Certain rules
      • OSI reference model: the model is too idealized to be widely popularized on the Internet

      • TCP/IP reference model (or TCP/IP Protocol): a de facto international standard.

IP

  • IP address: InetAddress

    • Uniquely identifies the computer (communication entity) on the Internet

    • Local loopback address: 127.0.0.1 hostname: localhost

    • IP address classification method 1: IPV4 and IPV6

      • IPV4: 4 bytes, 4 0-255. About 4.2 billion and 3 billion are in North America and 400 million in Asia. It was exhausted in early 2011. Expressed in dotted decimal system, such as 192.168.0.1
      • IPV6: 128 bits (16 bytes), written as 8 unsigned integers. Each integer is represented by four hexadecimal bits, separated by colons (:), such as 3ffe:3201:1401:1280:c8ff:fe4d:db39:1984
    • IP address classification method 2: public address * * (for World Wide Web use) and private address (for LAN use) * *. 192.168. At the beginning is the private address. The range is 192.168.0.0 – 192.168.255.255, which is specially used within the organization

    • Features: not easy to remember

  • How to instantiate InetAddress: two methods: getByName(String host) getLocalHost();

Two common methods: getHostName()/getHostAddress()

Port number

  • The port number identifies the process (program) running on the computer
  • Different processes have different port numbers
  • It is specified as a 16 bit integer 0 ~ 65535.
  • Port classification:
    • **Recognized port: * * 0 ~ 1023. Occupied by predefined service communication (e.g. HTTP occupies port 80, FTP occupies port 21, Telnet occupies port 23)
    • **Registration port: * * 1024 ~ 49151. Assigned to a user process or application. (for example, Tomcat occupies port 8080, MySQL occupies port 3306, Oracle occupies port 1521, etc.).
    • Dynamic * * / private port: * * 49152 ~ 65535**
  • The combination of port number and IP address yields a network Socket: Socket * *.

TCP/IP protocol cluster

  • Before using TCP protocol, a TCP connection must be established to form a data transmission channel

  • Before transmission, the "three-time handshake" mode is adopted for point-to-point communication, which is reliable

  • Two application processes that communicate with TCP protocol: client and server.

  • A large amount of data can be transmitted in the connection

  • After transmission, the established connection needs to be released, which is inefficient

  • @Test
    public void client(){
        OutputStream outputStream=null;
        Socket socket=null;
        try {
            //1. Create a Socket object to indicate IP and port number
            InetAddress inetAddress=InetAddress.getByName("127.0.0.1");
            socket=new Socket(inetAddress,8866);
    
            //2. Obtain an output stream for outputting data
            outputStream=socket.getOutputStream();
            //3. Write operation
            outputStream.write("Zhang Haohui studies java".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4. Close resources
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
    
    }
    
    //Server
    @Test
    public void server(){
        InputStream inputStream= null;
        ByteArrayOutputStream bytes= null;
        Socket socket1=null;
        ServerSocket socket=null;
        try {
            //1. Define a ServerSocket object storage port
            socket=new ServerSocket(8866);
            //2. Create a Socket object with the port number of the ServerSocket object
            socket1=socket.accept();
            //3. Create input stream
            inputStream = socket1.getInputStream();
            //4. Conversion flow
            bytes = new ByteArrayOutputStream();
            byte[] bytes1 = new byte[20];
    
            int len;
            while((len=inputStream.read(bytes1))!=-1){
                bytes.write(bytes1,0,len);
            }
    
            System.out.println(bytes.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //5. Close the flow
            if(bytes!=null){
                try {
                    bytes.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket1!=null){
                try {
                    socket1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
  • @Test
    public void client(){
        Socket socket=null;
        OutputStream outputStream=null;
        FileInputStream fileInputStream=null;
        try {
            socket=new Socket(InetAddress.getByName("127.0.0.1"),8888);
            outputStream=socket.getOutputStream();
            fileInputStream=new FileInputStream("zjm.jpg");
    
            byte[] bytes=new byte[1024];
            int len;
            while((len=fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fileInputStream!=null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    @Test
    public void server(){
        Socket socket=null;
        InputStream inputStream=null;
        FileOutputStream file=null;
    
        try {
            socket=new ServerSocket(8888).accept();
            file=new FileOutputStream("zjm3.jpg");
            inputStream=socket.getInputStream();
            byte[] bytes=new byte[1024];
            int len;
            while((len=inputStream.read(bytes))!=-1){
                file.write(bytes,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(file!=null){
                try {
                    file.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    

UDP/IP protocol cluster

  • Encapsulate the data, source and destination into data packets without establishing a connection

  • The size of each datagram is limited to 64K

  • Whether the sending party is ready or not, the receiving party does not confirm the receipt, so it is unreliable

  • Can broadcast and send

  • At the end of sending data, there is no need to release resources, low overhead and high speed

  • technological process:

    1. Datagram socket and datagram packet
    2. Establish sender and receiver
    3. Create packet
    4. Call Socket sending and receiving methods
    5. Close Socket
  • The sender and receiver are two independent running programs

  • @Test
        public void send(){
            DatagramSocket socket =null;
            try {
                socket = new DatagramSocket();
                String str="Zhang Haohui, come on today";
                byte[] bytes=str.getBytes();
                InetAddress inet=InetAddress.getLocalHost();
                DatagramPacket packet = new DatagramPacket(bytes,bytes.length,inet,8888);
                socket.send(packet);
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(socket!=null){
                    try {
                        socket.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    
        @Test
        public void accept(){
    
            DatagramSocket socket =null;
            DatagramPacket packet =null;
            try {
                socket = new DatagramSocket(8888);
    
                byte[] bytes=new byte[10];
                packet = new DatagramPacket(bytes,0,bytes.length);
                socket.receive(packet);
                FileOutputStream file=new FileOutputStream("hello.txt");
                file.write(packet.getData(),0, packet.getLength());
    
                System.out.println(new String(packet.getData(),0,packet.getLength()));
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(socket!=null){
                    try {
                        socket.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    

URL programming

  1. URL: uniform resource locator, corresponding to a resource address on the Internet
  2. Format: Protocol hostname port number resource address parameter list
  3. Common methods:
    • public String getProtocol() gets the protocol name of the URL
    • public String getHost() gets the host name of the URL
    • public String getPort() gets the port number of the URL
    • public String getPath() gets the file path of the URL
    • public String getFile() gets the file name of the URL
    • public String getQuery() gets the query name of the URL

Keywords: Java

Added by compbry15 on Thu, 27 Jan 2022 23:53:45 +0200