java network programming foundation

Network programming

1. Purpose of network programming
  • Share resources
  • Realize data transmission and download
1.1 software architecture

Network communication is based on software structure: C/S structure and B/S structure

  • The full name of C/S architecture is Client /Server architecture, that is, customer service and server

    • Common programs such as QQ, Xunlei, IDEA and other software
    • Advantage: the customer experience is good, because the customer needs to download the customer service terminal
    • Disadvantages: it is troublesome to download and maintain later
  • The full name of B/S architecture is Browser/Server architecture, which is browser and server architecture

    • Common browsers: Google, Firefox, etc
    • Common software: erudite Valley, Jingdong, Taobao
    • Advantages: it is convenient to browse these servers directly on the web without downloading
    • Disadvantages: poor network, poor customer experience
1.2 three elements of network communication

There must be a certain agreement in Netcom Communication, otherwise the communication between computers cannot be realized

  1. agreement:

    • The communication rules that must be agreed in advance and abided by each other for the communication between computer network client and server
    • HTTP , FTP , TCP , UDP , SSH , SMTP
  2. IP address:

    • ip address Internet Protocol Address
    • There are two types of IP addresses
      • IPv4:4 bytes, 32-bit composition 192.168.70.70 value of each bit is 0-225
      • IPv6: IP 128 bits can be allocated to all devices
    • Local IP address: 127.0.0.1 or localhost

Note: if you only get the IP address, you can connect to that computer, not to specific applications

3. Port number:

  • The port number is used to uniquely identify the process in the device, that is, the application
  • An integer in two bytes with a value range of 0-65535
    • Port numbers between 0 and 1023 are used for some well-known network services and Applications
    • Ordinary applications need to use port numbers above 1024

Conclusion: using these three elements, we can realize network communication

1.3 layer and protocol of network communication
-------------------------------------------------------------------------------
Application layer: Applications (QQ, wechat, browser), possible protocols (HTTP,FTP,SMTP) usually programmers only need to care about this layer
------------------------------------------------------------------------------
Transport layer: TCP/IP protocol - UDP protocol: a protocol that computer network engineers need to be proficient in
-----------------------------------------------------------------
Network layer: IP protocol encapsulates its own IP and the IP and port of the other party
-----------------------------------------------------------------
Data link layer: access to hardware (Network)
-----------------------------------------------------------------
1.4 InetAddress class

In java, we use InetAddress class to represent the object of IP address,

This class cannot create an instance. It returns an IP address object through a static method.

InetAddress class member method:

  • static InetAddress getLocalHost() gets the local host IP address object
  • static InetAddress getByName(String host) gets the corresponding IP address object according to the IP address string or host name
  • String getHostName() get hostname
  • String getHostAddress() to get the IP address string

Test code

package com.net;

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

public class InetAddressDemo01 {
    public static void main(String[] args) throws IOException {
        //Get IP address object
        InetAddress localHost = InetAddress.getLocalHost();
        System.out.println(localHost.getHostAddress());// Get ip address
        System.out.println(localHost.getHostName()); //Get host name

       //Obtain domain name ip object with domain name
        InetAddress ip2 = InetAddress.getByName("www.baidu.com");
        System.out.println(ip2.getHostAddress());
        System.out.println(ip2.getHostName());

        // Judge whether it can pass: test whether it can pass before Ping 3S
        System.out.println(ip2.isReachable(3000)); // ping
    }
}

Operation result:

1.5 introduction to UDP communication

1. Features of UDP protocol:

  • Protocol for connectionless
  • The sender only sends and does not confirm whether the other party can receive it
  • Data transmission based on data package
  • The packet size limit for sending data is within 64KB
  • Because facing connectionless, fast, but unreliable, data will be lost!

2. Two classes related to UDP protocol:

Detailed analysis of datagram packet class constructor:

  1. According to the different constructor parameters, it is divided into the sender constructor and the receiver constructor
    1.1 constructors for the sender:
    New datagram packet (byte [] buf, int length, InetAddress address, int port) is used to create the sender object
    buf: content to be sent, byte array
    Length: the length of the content to be sent, in bytes
    Address: IP address object of the receiver
    Port: port number of the receiver

    1.2 constructor for receiving end:
    New datagram packet (byte [] buf, int length) creates the packet object of the receiver
    buf: used to store received content
    Length: the length that can receive content

  2. Implementation ideas:

      1. Create a datagram packet (packet object) object to encapsulate the data to be sent. It only stores the encapsulated data, and the datagram socket class is used to send the data
      2. Create a class received by the server to receive the data sent by the customer service
    
package com.net;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPClientDemo01 {
    public static void main(String[] args) throws IOException {
        System.out.println("Customer service start");
        byte[] bytes = "Hello, have you eaten".getBytes();//What to send
        DatagramPacket packet = new DatagramPacket(bytes, bytes.length, InetAddress.getLocalHost(), 9966);
        DatagramSocket socket = new DatagramSocket();
        socket.send(packet); //Send packet object
        socket.close();//close resource
    }
}
package com.net;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class UDPServerDemo02 {
    public static void main(String[] args) {
        System.out.println("Server side startup");
        byte[] bytes = new byte[1024*64]; //Create a packet object to receive the client
        DatagramPacket packet = new DatagramPacket(bytes,bytes.length);
        //Create a receiver object
        DatagramSocket socket;
            try {
                socket = new DatagramSocket(9966);//This port number should be consistent with that of the sender
                //Start receiving
                socket.receive(packet);
                int len = packet.getLength();//Get received length
                String str = new String(bytes,0,len);
                System.out.println(str);
                System.out.println("Server received");

                //The server can also obtain the IP and port of the client sending the information
                String ip = packet.getAddress().getHostAddress();
                int port = packet.getPort();
                System.out.println("Sender's ip address"+ip+"\n"+"The port number of the other party is:"+port);
                socket.close();
            } catch (SocketException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
}

Row result:


1.6 TCP communication protocol details:
  1. TCP/IP is a safe and reliable transmission protocol. Data will be sent only after the server is successfully connected,

It is mainly used for file upload and download, email sending and receiving, remote login, because we need to ensure that no data is lost

  1. Features of TCP/IP protocol:
  • Connection oriented protocol
  • The client can only send the data to the server actively. After receiving the data, the server can respond to the data to the client
  • The connection is established by three handshakes, and the connection successfully forms a data transmission channel
  • Disconnect with four waves
  • Data transmission based on IO stream
  • There is no limit to the size of data transferred
  • Because of the connection oriented protocol, it is slow but reliable
  1. TCP related classes in Java: socket and ServerSocket

    The construction method of Socket class:

  • Socket(String host, int port) incoming IP address and port number

  • Note: as long as this method is executed, the specified server program will be connected immediately. If the connection is not successful, an exception will be thrown. If the connection is successful, it means three handshakes are passed.

    Common methods of Socket class:

  • OutputStream getOutputStream(); get byte output stream object

  • InputStream getInputStream(); get byte input stream object

ServerSocket represents the server object:

  • public ServerSocket(int port) gets the port number of the customer service terminal

  • public Socket accept() receives the connection request from the customer service end and returns the Socket object after the connection is successful

    Code implementation:

    package com.net;
    
    import java.io.IOException;
    import java.io.OutputStream;
    import java.io.PrintStream;
    import java.net.Socket;
    
    public class ClientDemo01 {
        public static void main(String[] args) throws IOException {
            //1. Create customer service object
            Socket socket = new Socket("LocalHost", 9966);
            //2. Get the byte output stream from the socket pipe
            OutputStream outputStream = socket.getOutputStream();
            //3. Convert low-level flow to high-level output flow
            PrintStream ps = new PrintStream(outputStream);
            //send message
            ps.println("Hello server, I'm customer service");
            ps.flush();//Refresh
            System.out.println("Customer service end sending data completed~");
        }
    }
    
    package com.net;
    
    import java.io.*;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    public class ServerDemo01 {
        public static void main(String[] args) throws IOException {
            System.out.println("Server start to enable");
            //1. Create the server-side object
            ServerSocket serverSocket = new ServerSocket(9966);
            //2. Start waiting for socket connection of receiving customer service terminal
            Socket acceptSocket = serverSocket.accept();
            //3. Connect successfully and get the byte input stream of socket
            InputStream inputStream = acceptSocket.getInputStream();
            //4. Transfer byte input to character input stream
            Reader reader = new  InputStreamReader(inputStream);
            //5. Wrap character input stream into buffered character input stream
            BufferedReader br = new BufferedReader(reader);
            //6. Read line by line to think that what is sent is sent line by line
            String line;
            if((line = br.readLine())!=null){
                System.out.println(line);
            }
        }
    }
    


Improve customer service manual data sending

package com.net;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

public class ClientDemo01 {
    public static void main(String[] args) throws IOException {
        //1. Create customer service object
        Socket socket = new Socket("LocalHost", 9966);
        //2. Get the byte output stream from the socket pipe
        OutputStream outputStream = socket.getOutputStream();
        //3. Convert low-level flow to high-level output flow
        PrintStream ps = new PrintStream(outputStream);
        //Send message all the time
        while (true){
            Scanner scanner = new Scanner(System.in);
            System.out.print("Customer service:");
            ps.println(scanner.nextLine());//Line by line writing
            ps.flush();
        }
    }
}
package com.net;

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

public class ServerDemo01 {
    public static void main(String[] args) throws IOException {
        System.out.println("Server start to enable");
        //1. Create the server-side object
        ServerSocket serverSocket = new ServerSocket(9966);
        //2. Start waiting for socket connection of receiving customer service terminal
        Socket acceptSocket = serverSocket.accept();
        //3. Connect successfully and get the byte input stream of socket
        InputStream inputStream = acceptSocket.getInputStream();
        //4. Transfer byte input to character input stream
        Reader reader = new  InputStreamReader(inputStream);
        //5. Wrap character input stream into buffered character input stream
        BufferedReader br = new BufferedReader(reader);
        //6. Keep reading
        String line;
        while ((line = br.readLine())!= null){
            System.out.println(line);
        }
    }
}


Multithreading for sending data to multiple customer service terminals

package com.net;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
public class ClientDemo01 {
    public static void main(String[] args) throws IOException {
        //1. Create customer service object
        Socket socket = new Socket("LocalHost", 9966);
        //2. Get the byte output stream from the socket pipe
        OutputStream outputStream = socket.getOutputStream();
        //3. Convert low-level flow to high-level output flow
        PrintStream ps = new PrintStream(outputStream);
        //Send message all the time
        while (true){
            Scanner scanner = new Scanner(System.in);
            System.out.print("Customer service:");
            ps.println(scanner.nextLine());//Line by line writing
            ps.flush();
        }
    }
}
package com.net;

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

public class ServerDemo02 {
    public static void main(String[] args) throws IOException {
        System.out.println("Server side enable");
        //1. Get server object
        ServerSocket serverSocket = new ServerSocket(9966);
        //2. Loop to receive customer service objects of different threads
        while(true){
            Socket acceptSocket = serverSocket.accept();
            Thread thread = new ServerReaderThread(acceptSocket);
            thread.start();
        }
    }
}
class ServerReaderThread extends Thread{
    Socket socket;
    public ServerReaderThread(Socket acceptSocket) {
        this.socket = acceptSocket;
    }
    @Override
    public void run() {
        try {
            //3. Get the byte input stream of socket pipe
            InputStream inputStream = socket.getInputStream();
            //4. Package into buffer stream
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            //5. Read data
            String line ;
            while ((line = br.readLine())!=null){
                System.out.print(socket.getRemoteSocketAddress());//Get the IP address of the current thread
                System.out.println(line);
            }
        } catch (IOException e) {
            System.out.println(socket.getRemoteSocketAddress()+"It's offline~");
        }
    }
}

Operation diagram:


Tags: socket Java network Programming

Posted on Thu, 25 Jun 2020 02:49:03 -0400 by RussW