Java Web Basics - network programming
Content outline of this paper
1. Why network programming?
It is controlled by code to enable data interaction between the processes of two hosts
what we call network programming is to communicate through the network. Specifically, it refers to different hosts connected by the network. Specifically, it refers to the process between two hosts
For example:
I sent a message using qq. The message was sent to the Tencent server (corresponding server process) through the qq client process on my computer, and then the Tencent server process forwarded the message to the qq process on the other computer
this is the most basic thing we do through network programming. Through network programming, we can achieve the effect that the horizon is close to each other, and many hosts on the Internet can work together. At this time, the programs we write can do too much... So network programming is a very common demand scenario.
2. What is network programming
network programming refers to that the host on the network realizes network communication (or network data transmission) by programming through different processes.
of course, we just need to meet the different processes; Therefore, even if it is the same host, as long as it is a different process and transmits data based on the network, it also belongs to network programming. In particular, for development, under limited conditions, it is generally to run multiple processes in one host to complete network programming.
However, we must be clear that our purpose is to provide different hosts on the network to transmit data resources based on the network:
Process A: programming to obtain network resources
Process B: programming to provide network resources
So how do we use programs for network programming?
the operating system encapsulates some related operations of network programming and provides a set of API s for programmers to use
These related operations are the functions provided by the operating system to access the hardware device of the network core: network card
the network card is also managed by the operating system, so the operating system manages the network card and provides some APIs to programmers. We can directly use the API to operate network communication. This is the basic situation of network programming
The network programming API provided by the operating system is named socket API, which is a set of API interfaces for network communication provided by the operating system
Socket socket
since the socket API provided by the operating system is a C language style interface, it can not be used directly in Java. JDK encapsulates the socket API of C language, and there is a group of classes in the standard library. This group of classes can enable us to carry out network programming, but we should know that, This group of classes is still essentially the socket API provided by the calling operating system
So we have a problem here?
Can Java call C language functions?
Yes, many languages can call each other. The core principle of cross language call is to understand the abi (binary programming interface) binary instruction rules of the corresponding language
3. Basic concepts in network programming
(1) Sender and receiver
During a network data transmission:
Sender: the sender process of data, called the sender. The sending host is the source host in network communication.
Receiving end: the process of receiving data, which is called receiving end. The receiving host is the destination host in network communication.
Transceiver: both ends of the sender and receiver, also referred to as the transceiver.
Note: the sending end and the receiving end are only relative, which is the concept of data flow after a network data transmission.
(2) Request and response
Generally speaking, acquiring a network resource involves two network data transmissions:
First time: request data transmission
Second: send response data.
Like ordering a fried rice in a fast food restaurant:
First, request: order a fried rice, and then have the corresponding response provided by the fast food restaurant: provide a fried rice
(3) Client and server
Server: in common network data transmission scenarios, the process providing services is called the server, which can provide external services.
Client: the process that obtains the service, called the client.
For services, it generally provides:
Client gets service resources
Like working in a bank:
The bank provides deposit service: the user (client) saves resources (cash) in the bank (server)
The bank provides withdrawal service: the user (client) obtains the server resources (cash kept by the bank for the user)
(4) Common client server models
In the most common scenario, the client refers to the program for users, and the server refers to the program that provides user services:
1. The client sends a request to the server first
2. The server performs corresponding business processing according to the requested data
3. The server returns a response: send the business processing result
4. The client displays the processing results according to the response data (display the obtained resources or prompt to save the processing results of resources)
This client server model is very common in network programming, and we must be familiar with the process.
in order to understand every process here, let's compare a restaurant to a server
then, I come to this restaurant for dinner. First of all, I want to order. I say to have a rice covered with double cooked pork, which is to send a request. Then the restaurant brings the dishes back, which is equivalent to returning the response. The period from ordering to serving is equivalent to the time the restaurant has to cook the meal. Note that whether a restaurant is good or not depends on the cooking process, Good business is good. The process of cooking is to calculate the response according to the request. When the food is ready, the waiter brings the food to me. This is the response display.
well, this is some basic knowledge about network programming that we introduce to you. We specifically write an application scenario of an echo server and client
4. Echo server code
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; public class UdpEchoSever { private DatagramSocket socket = null; // Port indicates the port number // When the server starts, it needs to be associated with the previous port number // When the data is received, it will decide which process to send the data to according to the port number // Although the type int written here is port, in fact, the port number is a two byte unsigned integer // Range: 0 ~ 65535 public UdpEchoSever(int port) throws SocketException { this.socket = new DatagramSocket(port); } // Use this method to start the server public void start() throws IOException { System.out.println("Server startup!!"); // Servers generally run continuously (7 * 24) while (true) { // 1. Read the request. The current server does not know when the client sends the request. The receive method also blocks // If there is a request, the receive will return // The receive parameter datagram packet is an output parameter, and the data read in the socket will be set to the object of this parameter // When constructing a datagram packet, you need to specify a buffer, usually byte [] DatagramPacket requestPacket = new DatagramPacket(new byte[4096],4096); // This packet object requires the programmer to customize the buffer size socket.receive(requestPacket); // Take out the contents of the reuqestPacket object as a string String request = new String(requestPacket.getData(),0,requestPacket.getLength()); // 2. Calculate the response according to the request String response = process(request); // 3. To write back the response to the customer, you also need to construct a datagram packet // The length set here for datagram packet must be "number of bytes" // If you go directly to response Length() the expression obtained here is the length of the string, that is, "the number of characters" // When the current responsePacket is constructed, you also need to specify who the packet is to be sent to // In fact, the sending target is the party sending the request DatagramPacket responsePacket = new DatagramPacket(response.getBytes(), response.getBytes().length, requestPacket.getSocketAddress() ); socket.send(responsePacket); // 4. Log printing String log = String.format("[%s:%d] req: %s resp: %s", requestPacket.getAddress().toString(), requestPacket.getPort(), request,response); } } // The function of the process method here is to calculate the response according to the request // Currently, it is an echo server, which returns the client's request directly private String process(String request) { return request; } public static void main(String[] args) throws IOException { UdpEchoSever udpEchoSever = new UdpEchoSever(9090); udpEchoSever.start(); } }
Server code considerations
5. Echo client code
import java.io.IOException; import java.net.*; import java.util.Scanner; public class UdpEchoClient { private DatagramSocket socket = null; private String severIp; private int port; public UdpEchoClient(String severIp,int port) throws SocketException { this.socket = new DatagramSocket(); // There is no need to specify the port number here, which is assigned by the system itself this.severIp = severIp; this.port = port; } public void start() throws IOException { Scanner scanner = new Scanner(System.in); System.out.println("Client startup!"); while(true){ // 1. Read a data from the standard input and construct the request System.out.print("->"); String request = scanner.nextLine(); if(request.equals("exit")){ System.out.println("Client offline!"); return; } // 2. Construct this string into a Udp request and send data // The datagram packet here should not only contain specific data, but also include who the data is to be sent to DatagramPacket requestPacket = new DatagramPacket( request.getBytes(), request.getBytes().length, InetAddress.getByName(severIp), port ); socket.send(requestPacket); // 3. Try to read the corresponding from the server DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096); socket.receive(responsePacket); String response = new String(responsePacket.getData(),0,responsePacket.getLength()); // 4. Print log String log = String.format("req: %s resp: %s",request,response); System.out.println(log); } } public static void main(String[] args) throws IOException { // Loopback IP: 127.0.0.1 loopback IP is equivalent to the host itself // At present, the client and server are on the same host, so the server Ip written in the client is 127.0.0.1 // If you are on a different host, you need to write it on the server Ip of the corresponding host UdpEchoClient udpEchoClient = new UdpEchoClient("127.0.0.1",9090); udpEchoClient.start(); } }
Client code considerations
Because the client sends a request to the server first (determined by the definition of the client server concept)
Since the client sends first, the client must know the IP and port number of the server first
If the server receives the data from the client, the server will know the IP and port number of the client
Operation display
Enter the results in the client in turn, print the request and response, at the same time, the server prints the client host and port number and request response, the client enters exit, and the client goes offline
that's all for today's network programming. I hope you can practice more. Thank you for your reading and appreciation