Summary of network programming

Network programming

Overview of network programming

Computer network:

It is a system that connects computers with independent functions in different geographical regions with communication lines through communication equipment, and has fully functional software to realize information resource sharing and information transmission.

Network programming:

java language supports the network. java encapsulates the network implementation details into different classes, which are controlled by the JVM. Using these classes to develop programs can realize the data transmission of network programming.

Purpose of network programming:

Communicate with other computers directly or indirectly through network protocol.

Core elements of network programming:

There are two main problems in network programming:

  • How to accurately locate one or more hosts on the network;
  • How to efficiently and reliably transmit data after finding the host.

How to accurately find a host in the network: through IP (find host) + port number (determine which program in the host);

How to transmit data efficiently and reliably: as long as it depends on the communication protocol used (TCP and UDP).

IP is the unique identification of the host. Under Windows system, open cmd, enter ipconfig command, and press enter to view the local IP address. The local loopback address (127.0.0.1) represents the local virtual interface of the device.

Port number is an integer number label of applications in the computer, which is used to distinguish different applications. 065535 is a valid port number, in which 01024 has been occupied, so when we want to define the port number for some programs, we should select an integer in the range of 1024 ~ 65535.

Communication protocol both parties agree on which way to transmit data.

There are two important transport protocols in the transport layer:

TCP

Transmission Control Protocol (TCP): it is a connection oriented, reliable and byte stream based transport layer communication protocol.

Before using TCP, it is necessary to establish a TCP connection to form a transmission data channel, in which a large number of data transmission can be carried out.

Before transmission, "three handshakes" are adopted, including two communication processes: client and server.

After data transmission, the connection needs to be disconnected, which is inefficient.

A "four wave" is required when disconnecting.

Simple understanding of "three handshakes, four waves"


UDP

User Datagram Protocol (UDP): a transmission protocol that supports wireless connection. This protocol is called User Datagram Protocol.

When using UDP, the data, source and destination are encapsulated into data packets, and there is no need to establish a transmission data channel.

The size of each packet is limited to 64k.

Because it does not need to establish a link, it is unreliable, and there is no need to release resources at the end, which is fast.

network model

TCP programming

Working process of client Socket:

  1. Create Socket According to the IP address and port number of the server, the Socket class object is constructed. If the server responds, it is linked to the communication link of the server. Otherwise, the link fails and an exception occurs.

  2. Open the I / O stream connected to the Socket Use getInputStream() method to obtain the input stream and getOutputStream() method to obtain the output stream for data transmission.

  3. Read and write sockets according to certain protocols

  4. Close Socket Disconnect the link release line.

    client

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class Client1 {
    public static void main(String[] args) throws IOException {
        //Create a client Socket and link the host when creating it. If you cannot connect, an error will be reported
        Socket socket = new Socket("127.0.0.1",9898);
        //The message getOutputStream() sent to the server returns data of type OutputStream
        OutputStream out = socket.getOutputStream();
                    out.write("Hello server".getBytes("UTF-8"));

         //Read the message returned by the server
        InputStream in = socket.getInputStream();
        byte[] bytes = new byte[1024];
        int size =in.read(bytes);
        String msg = new String(bytes,0,size);
        System.out.println(msg);

    }
}

Server side

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9898);
        System.out.println("Server on,Waiting for client connection!");
        //Monitoring: once a client sends a request to the server, it will get the Socket of the corresponding client
        Socket socket = serverSocket.accept();
        System.out.println("Link successful");
        //Output messages sent by clients
        InputStream in = socket.getInputStream();
        byte[] b = new byte[1024];
        int size =in.read(b);
        String mag = new String(b,0,size,"utf-8");
        System.out.println(mag);
        //The server sends data to the client
        OutputStream out = socket.getOutputStream();
        out.write("Hello client,What's the matter?".getBytes("utf-8"));
    }
}

The above code can only be sent once, and multiple sending can be realized by introducing a cycle:

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
//client
public class Client {
    public static void main(String[] args) throws IOException {
        //Create a Socket client, including the IP address and port number of the server,
        Socket socket = new Socket("127.0.0.1",9999);
        Scanner scanner = new Scanner(System.in);
        //Introduce DataOutputStream to process stream data output
        DataOutputStream dout = new 				DataOutputStream(socket.getOutputStream());
        DataInputStream din = new DataInputStream(socket.getInputStream());
        while (true){
            System.out.println("Client input:");
            String msg = scanner.next();
            dout.writeUTF(msg);
            System.out.println("Server side theory:"+din.readUTF());
        }
    }
}
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
//The server
public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(9999);
        Socket socket = server.accept();
        Scanner scanner = new Scanner(System.in);
        System.out.println("Connected");
        DataInputStream din = new DataInputStream(socket.getInputStream());
        DataOutputStream dout = new DataOutputStream(socket.getOutputStream());
        while (true){
            String msg = din.readUTF();
            System.out.println(msg);
            //Server send
            String msg2 = scanner.next();
            dout.writeUTF(msg2);
        }
    }
}

After the second modification, the client can only send it once and the server can send it once. In this way, the cycle can not reach the client or the server all the time.

UDP programming

Datagram socket and datagram packet implement the network program based on UDP protocol.

Datagram socket: send data

Datagram packet object encapsulates datagram, including data content, IP address and port number of sender and IP address and port number of receiver.

Each datagram of UDP protocol gives complete address information, so there is no need to establish a link between the sender and the receiver.

Sender and receiver are two independent programs. The sender just sends, regardless of whether the sender receives it or not.

UDP programming process:

  1. Datagram socket and datagram packet;
  2. Create sender and receiver;
  3. Establish datagram;
  4. Call the sending and receiving methods of Socket;
  5. Close Socket
import java.io.IOException;
import java.net.*;

public class Client {
    public static void main(String[] args) throws IOException {
        //Create DatagramSocket object to send datagrams
        DatagramSocket socket = new DatagramSocket();
        byte[] bytes ="How do you do!".getBytes("UTF-8");
        while (true){  
            //Create datagram packet package datagram, including data, data length, address and target port
            DatagramPacket dp = new DatagramPacket(bytes,bytes.length, InetAddress.getByName("192.168.1.143"),9999);
            //send out
            socket.send(dp);
        }
    }
}

public class Server {
    public static void main(String[] args) throws IOException {
        //The receiving end specifies the listening port
        DatagramSocket dsocket = new DatagramSocket(9999);

        byte[] bytes = new byte[1024];
        while (true){
               //Packaging datagram
            DatagramPacket dp = new DatagramPacket(bytes,bytes.length);
            //receive
            dsocket.receive(dp);
            //   Converts the length of the sender's message to the length of the sender's message
            String msg = new String(bytes,0, dp.getLength());
            System.out.println(msg);
      }
    }
}

Tags: Java

Posted by n5tkn on Thu, 14 Apr 2022 18:49:52 +0930