Network Programming (1) Introduction to Network Programming

introduction

Network is the foundation of computer communication. Network programming is the best way to learn computer network. Usually standard computer network communication protocols are UDP and TCP (this does not include microcomputer network communication protocols (such as CAN, etc.)). First of all, Xiaoyuan Introduce several common interview questions.
1. What are the three elements of network programming?
Answer: The three elements of network programming are ip, transmission protocol, and port number.
2. How many network models are there? How to understand?
Answer: The common network models now include five-layer distribution, seven-layer division, and four-layer theory. The schematic diagrams of these divisions are as follows:
Seven-layer diagram and protocol explanations for each layer.
Insert picture description here
The 7-layer protocol and the 5-layer protocol compare
Insert picture description here
the protocols used in each iso layer.
Insert picture description here
3. What level does our programming belong to?
Answer: Our programming belongs to the application layer.
The following will focus on programming related to UDP and TCP.

UDP

UDP is a user protocol. It is a connectionless transport layer protocol that provides transaction-oriented simple and unreliable information transmission services. UDP features:
UDP is connectionless, that is, there is no need to create a connection when communicating, which can reduce network resource overhead (with fewer message bytes) and shorten the sending time. UDP can use common methods such as broadcasting.

Case

Use udp protocol 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");
    }
}

Run result
Sending end
Insert picture description here
receiving end
Insert picture description here

TCP

The TCP communication protocol is a reliable network protocol . It establishes a Socket object at both ends of the communication, thereby forming a network virtual link at both ends of the traffic. Once the virtual network link is established, the programs at both ends can pass the virtual link. Link to communicate.
The characteristics of the TCP protocol are
1, connection-oriented: the two parties using the TCP protocol communication must establish a connection before they can start data reading and writing. The TCP connection is full duplex, that is, the data reading and writing of both parties can be carried out through a connection. After completing the data exchange, both parties in the communication must disconnect to release resources. This connection of the TCP protocol is one-to-one, so applications based on broadcast and multicast (the target is multiple host addresses) cannot use the TCP server.
2 Streaming service: The manifestation of TCP's byte stream service is reflected in the fact 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 writes continuously When operating, the TCP module first puts these data into the TCP sending buffer. When the TCP module actually starts to send data, the data waiting to be sent in the send buffer may be encapsulated into one or more TCP segments for sending.
If you want to read computer network knowledge in more detail, please read this article on computer network .

Case number one

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 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){
          //如果不用socket.getOutPutStream来写的话,我们是否可以用bufferedWrite来写呢。
          //  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("发送客户端停止命令,客户端开始停止");
        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("接收到停止命令,开始释放服务端资源");
        br.close();
        ss.close();
    }
}

Operation result:
client
Insert picture description here
server
Insert picture description here

Case two

The client reads data from the txt file, sends the read data to the server, and the server regenerates a file after reading the content, 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() + "文件上传成功");
            System.out.println(Thread.currentThread().getName()+"文件上传成功");
            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("服务器的反馈是:"+data);

        brClient.close();

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

Running results
Server-side test results
Insert picture description here
Client-side test results The
Insert picture description here
running results meet expectations, and the case in this chapter is over.

Guess you like

Origin blog.csdn.net/xueshanfeitian/article/details/108870404