Introduction to network programming

introduction

Network is the basis of computer communication. Network programming is the best way to learn computer network. Generally, there are two standard computer network communication protocols: UDP and TCP (microcomputer network communication protocol (such as CAN, etc.) is not included here). First, ape introduces several common interview questions.
1. What are the three elements of network programming?
A: the three elements of network programming are ip, transmission protocol and port number.
2. How many network models are there? How to understand?
A: there are five layers of distribution, seven layers of distribution and four layers of distribution commonly used in the network model. The schematic diagrams of these methods are as follows:
7-layer schematic diagram and protocol interpretation of each layer.

Comparison between layer 7 protocol and layer 5 protocol

The protocol used by each iso layer.

3. Which layer does our programming belong to?
A: our programming belongs to the application layer.
The following will focus on the programming related to UDP and TCP.

UDP

UDP is a user protocol. It is a connectionless transport layer protocol, which provides transaction oriented simple and unreliable information transmission service. UDP features:
UDP is connectionless, that is, there is no need to create a connection during communication, which can reduce the overhead of network resources (less message bytes) and shorten the sending time. UDP can adopt broadcast and other traffic methods.

case

udp protocol is adopted to realize one receiving and one sending.
udp sender program

public class UDPSendDemo {
    public static void main(String[] args) throws IOException {
        DatagramSocket ds = new DatagramSocket();
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line;
        while ((line = br.readLine()) !=null){

            byte[] bytes = line.getBytes();
            DatagramPacket dp = new DatagramPacket(bytes, bytes.length,
                    InetAddress.getByName("192.168.168.1"), 12345);
            ds.send(dp);
            if("886".equals(line)){
                break;
            }
        }
        ds.close();
        br.close();
        System.out.println("send socket closed ");
    }
}

UDP receiver code

public class UDPReceiveDemo {
    public static void main(String[] args) throws IOException {
        DatagramSocket ds = new DatagramSocket(12345);
        while (true){
            byte[] bytes = new byte[1024];
            DatagramPacket dp = new DatagramPacket(bytes, bytes.length);
            ds.receive(dp);
            String data = new String(dp.getData(), 0, dp.getLength());
            System.out.println("data is ,"+data);
            if("886".equals(data)){
                break;
            }
        }
        ds.close();
        System.out.println("receive socket closed");
    }
}

Operation results
Sender

receiving end

TCP

TCP communication protocol is a reliable network protocol. It establishes a Socket object at both ends of the communication, so as to form a network virtual link at both ends of the passage. Once the virtual network link is established, the programs at both ends can communicate through the virtual link.
The characteristics of TCP protocol are
1. Connection oriented: both parties using TCP protocol must establish a connection before starting data reading and writing. TCP connection is full duplex, that is, data reading and writing of both parties can be carried out through one connection. After the data exchange is completed, both sides of the communication must disconnect to release resources. This connection of TCP protocol is one-to-one, so applications based on broadcast and multicast (targeting multiple host addresses) cannot use TCP services.
2 streaming service: the expression form of TCP byte stream service is that there is no quantitative relationship between the number of write operations performed by the sender and the number of read operations performed by the receiver. When the sender application performs multiple write operations continuously, the TCP module first puts these data into the TCP transmission buffer. When the TCP module really starts sending data, the data waiting to be sent in the transmission buffer may be encapsulated into one or more TCP message segments.
If you want to see the knowledge of computer network in more detail, please see the boss's computer network article.

Case 1

The client sends data, and the server receives the data and displays it on the console. When the client sends a termination command, both the client and the server should terminate the service.
client

public class ClientDemo {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("192.168.152.1", 10001);
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

        String line;
        while ((line=br.readLine())!=null){
          //If you don't use socket If getoutputstream is used to write, can we use bufferedWrite to write.
          //  OutputStream os = socket.getOutputStream();
          // os.write(line.getBytes());
            bw.write(line,0,line.length());
            bw.newLine();
            bw.flush();
            if ("999".equals(line)){
                break;
            }
        }
        System.out.println("Send the client stop command and the client starts to stop");
        br.close();
        bw.close();
        socket.close();
    }
}

Server

public class ServerDemo {
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(10001);
        Socket accept = ss.accept();

        BufferedReader br = new BufferedReader(new InputStreamReader(accept.getInputStream()));
        String line;
        String str=null;
        while (true){

            while ((line=br.readLine())!=null){
                str=line;
                System.out.println(line);
            }
            if(str.equals("999")){
                break;
            }
        }
        System.out.println("After receiving the stop command, start to release the server resources");
        br.close();
        ss.close();
    }
}

Operation results:
client

Server

Case 2

The client reads the data from the txt file and sends the read data to the server. After reading the content, the server regenerates a file and writes the received content into the file.
Server thread class

public class ServerThread implements Runnable {
    private Socket accept;
    public ServerThread(Socket accept) {
        this.accept = accept;
    }
    @Override
    public void run() {
        BufferedReader br=null;
        BufferedWriter bw=null;
        BufferedWriter bwServer=null;
        try {
             br = new BufferedReader(new InputStreamReader(accept.getInputStream()));
             bw = new BufferedWriter(new FileWriter(Thread.currentThread().getName() + "copy.java"));
            String line;
            while ((line=br.readLine())!=null){
                bw.write(line);
                bw.newLine();
                bw.flush();
            }
            bwServer = new BufferedWriter(new OutputStreamWriter(accept.getOutputStream()));
            bwServer.write(Thread.currentThread().getName() + "File uploaded successfully");
            System.out.println(Thread.currentThread().getName()+"File uploaded successfully");
            bwServer.newLine();
            bwServer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                br.close();
                bw.close();
                bwServer.close();
                accept.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Server main class

public class Server02Demo {
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(10001);
        while (true){
            Socket accept = ss.accept();
            new Thread(new ServerThread(accept)).start();
        }
    }
}

Client class

public class Client02Demo {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("192.168.152.1",10001);
        BufferedReader br = new BufferedReader(new FileReader("reader&writer\\Client.txt"));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

        String line;
        while ((line = br.readLine())!=null){
            bw.write(line);
            bw.newLine();
            bw.flush();
        }

        socket.shutdownOutput();
        BufferedReader brClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String data = brClient.readLine();
        System.out.println("The feedback from the server is:"+data);

        brClient.close();

        br.close();
        bw.close();
        socket.close();
    }
}

Operation results
Server test results

Client test results

The operation results meet the expectations, and the case in this chapter ends.

Tags: Java Back-end

Posted by Digwood on Sat, 14 May 2022 07:31:03 +0300