Directory
1. Why do you need network programming?
2. What is network programming?
3. Sending end and receiving end
4. Request and Response
5. Client and server
6. How to do network programming (Socket socket)
1. How to do network programming
2. The difference between TCP and UDP
1. Stream socket: use the transport layer TCP protocol
2. Datagram socket: use the transport layer UDP protocol
3. Example comparison between TCP and UDP
7. Using UDP datagram socket programming in Java
1. Classes and methods
1. DatagramSocket construction method
2. DatagramSocket common method
3. Datagram Packet API
1. DatagramPacket construction method
2. DatagramPacket method is common
8. Implement a simple UDP echo server to the client
Server steps:
Server code:
2. Client steps
Client code:
code show as below:
The result display:
1. Why do you need network programming?
- The so-called network resources are actually various data resources that can be obtained in the network.
- And all network resources are transmitted through network programming
2.What is web programming?
Network programming refers to the host on the network, through different processes, to achieve network communication (or network data transmission) in a programmed way
We only need to satisfy different processes, even if different processes of the same host, transfer data based on the network, also known as network programming
- Process A: Programming to get network resources
- Process B: Program to provide network resources
3. Sender and receiver
During a network data transfer:
- Sender: The sender process of the data is called the sender. The sending host is the source host in the network communication.
- Receiver: The receiver process of the data is called the receiver. The receiving end host is the destination host in the network communication.
4. Request and response
Generally speaking, obtaining a network resource involves two network data transmissions:
- First time: Sending of request data
- Second time: sending of response data.
5. Client and server
- Server: In a common network data transmission scenario, the process that provides the service is called the server, which can provide external services.
- Client: The process that obtains the service is called the client.
6. How to do network programming (SocketSocket)
1. How to do network programming
2. The difference between TCP and UDP
1. Stream socket: use transport layer TCP protocol
TCP, Transmission Control Protocol (Transmission Control Protocol), transport layer protocol
The following are the characteristics of TCP:
- There is a connection (for example, the two parties can communicate only after the call is connected)
- Reliable transmission (if a packet is lost, there will be a retransmission mechanism)
- Byte stream-oriented (you can hear a word when you say a word on the phone)
- There are receive buffers and send buffers
- No size limit (say as much as you want)
For the byte stream, it can be simply understood that the transmission data is based on the IO stream. The characteristic of stream data is that it is unbounded data when the IO stream is not closed. It can be sent multiple times. It can be received multiple times separately.
2. Datagram socket: use transport layer UDP protocol
UDP, namely User Datagram Protocol (User Datagram Protocol), transport layer protocol.
The following are the characteristics of UDP:
- No connection (whether the other party is powered on or not does not affect)
- Unreliable transmission (packet loss is lost)
- Datagram-oriented (send a whole text message to the other party before it can be read)
- With receive buffer, without send buffer
- Size is limited: a maximum of 64k can be transmitted at one time (SMS size will be limited)
For datagrams, it can be simply understood that the transmission data is piece by piece. If a piece of data is sent with 100 bytes, it must be sent at one time, and the reception must also receive 100 bytes at a time, and cannot be divided into 100 times. , receiving 1 byte at a time
3. Example comparison of TCP and UDP
7. Using UDPdatagram socket programming in Java
1. Classes and methods
DatagramSocket in the DatagramSocket API is a UDP Socket for sending and receiving UDP datagrams
1.DatagramSocket construction method
2.DatagramSocketcommon method
3.DatagramPacket API
DatagramPacket is the datagram sent and received by UDP Socket
1.DatagramPacket construction method
2. DatagramPacket method is normal
8. Implement a simple UDP echo server to the client
Server step:
- Define a DatagramSocket for the server side
- External services
<strong>Loop to receive user requests</strong> <strong>1. Create a DatagramPacket for receiving request data 2. Receive the request and fill the real content into the requestPacket 3. Get data from requestPacket 4. Get the response according to the request 5. Encapsulate the response into DatagramPacket 6. Send data 7. Print log</strong>
Server code:
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.nio.charset.StandardCharsets; public class UDP server { private DatagramSocket server; //Initialization, port number public UDP server (int port) throws Exception { if (port < 1024 || port > 65535) { throw new Exception("The port number must be between 1024~65535"); } this. server = new DatagramSocket(port); } //Provide services externally public void start () throws IOException { System.out.println("The server has started~~"); while (true) { //User receives the requested DatagramPacket DatagramPacket requestPacket = new DatagramPacket(new byte[1024],1024); //Accept the request server.receive(requestPacket); // Get and parse data from the request String request = new String(requestPacket.getData(),0,requestPacket.getLength()); / / Get the response according to the real request String response = processor (request); //Encapsulate the response DatagramPacket responsePacket = new DatagramPacket(response.getBytes(StandardCharsets.UTF_8),response.getBytes().length,requestPacket.getSocketAddress()); //send data server.send(responsePacket); //print log System.out.printf("[%s:%d] request: %s, response: %s.\\ ", requestPacket.getAddress().toString(), requestPacket.getPort(), request, response); } } private String processor(String request) { return "Little Koi " + request; } public static void main(String[] args) throws Exception { UDP server server = new UDP server(8888); server.start(); } }
2. Client steps
<strong>1. Define a DatagramSocket for the client 2. Define the IP address of the server and define the port number of the server 3. Loop to receive user input 1. Pack the request content into DatagramPacket 2. Send data 3. Receive the response 4. Fill the response data in the receive method 5. Parse the response data 6. Print log</strong>
Client code:
import java.io.IOException; import java.net.*; import java.nio.charset.StandardCharsets; import java.util.Scanner; public class UDPclient { private DatagramSocket client; private String serverIp; private int port; private SocketAddress address; public UDPclient (String severIp, int port) throws SocketException { this.client = new DatagramSocket(); this.severIp = severIp; this.port = port; this.address = new InetSocketAddress(severIp, port); } public void start () throws IOException { System.out.println("The client has started~~"); // Loop to receive user input Scanner sc = new Scanner(System.in); while (true) { System.out.println("Please enter the request"); String request = sc. next(); // 1. Pack the request content into a DatagramPacket DatagramPacket requestPacket = new DatagramPacket(request.getBytes(StandardCharsets.UTF_8),request.getBytes().length,address); //2. Send data client.send(requestPacket); //3. Receive the response DatagramPacket responsePacket = new DatagramPacket(new byte[1024],1024); //4. Fill the response data in the receive method client.receive(responsePacket); //5. Parse the response data String response = new String(responsePacket.getData(),0,responsePacket.getLength(),"UTF-8"); //6. Print log System.out.printf("request:%s, response : %s.\\ ",request,response); } } public static void main(String[] args) throws IOException { UDPclient pclient = new UDPclient("127.0.0.1",8888); pclient.start(); } }
In the above, we simply return the original request. In fact, we can also use the map to return the corresponding value through the key-value pair
The code is as follows:
import java.io.IOException; import java.net.*; import java.nio.charset.StandardCharsets; import java.util.Scanner; public class UDPclient { private DatagramSocket client; private String serverIp; private int port; private SocketAddress address; public UDPclient (String severIp, int port) throws SocketException { this.client = new DatagramSocket(); this.severIp = severIp; this.port = port; this.address = new InetSocketAddress(severIp, port); } public void start () throws IOException { System.out.println("The client has started~~"); // Loop to receive user input Scanner sc = new Scanner(System.in); while (true) { System.out.println("Please enter the request"); String request = sc. next(); // 1. Pack the request content into a DatagramPacket DatagramPacket requestPacket = new DatagramPacket(request.getBytes(StandardCharsets.UTF_8),request.getBytes().length,address); //2. Send data client.send(requestPacket); //3. Receive the response DatagramPacket responsePacket = new DatagramPacket(new byte[1024],1024); //4. Fill the response data in the receive method client.receive(responsePacket); //5. Parse the response data String response = new String(responsePacket.getData(),0,responsePacket.getLength(),"UTF-8"); //6. Print log System.out.printf("request:%s, response : %s.\\ ",request,response); } } public static void main(String[] args) throws IOException { UDPclient pclient = new UDPclient("127.0.0.1",8888); pclient.start(); } }