Network programming
Common sense of network programming------------------------------
At present, the mainstream network communication software includes: wechat, QQ, Feixin, Alibaba Wangwang, Momo, tantan
Seven layer network model------------------------------
OSI (Open System Interconnect), namely open system interconnection, is a network interconnection model studied by ISO (International Organization for Standardization) in 1985
OSI seven layer model and TCP/IP five layer model are divided as follows

When sending data, it is necessary to package the sent content layer by layer according to the above seven layer model and send it out
When receiving data, it is necessary to unpack and display the received content layer by layer in the reverse order of the above seven layer model
For example, when we buy a mobile phone, we need to package it, and when we accept it, we need to unpack it to get the mobile phone, that is, we can regard the mobile phone as a kind of data to describe the seven layer model
Relevant agreements------------------------------
There must be some conventions or rules for computers to realize communication in the network. These conventions and rules are called communication protocol
Such an agreement is that when you don't talk to others, that is, talking to yourself, you don't need some norms
When you want to talk to others, you need to make your words understood by others
Just like English, there are rules, so we need to have a rule on the network so that everyone can talk
For example, a microcomputer user in the network communicates with the operator of a mainframe
Because the character sets used by the two data terminals are different, the commands entered by the operator do not know each other
In order to be able to communicate, it is stipulated that each terminal should first transform the characters in its own character set into the characters in the standard character set before entering the network for transmission
After reaching the destination terminal, it is transformed into the characters of the terminal character set. For incompatible terminals, other features need to be converted in addition to the characters of the character set
Communication protocol can formulate unified standards for rate, transmission code, code structure, transmission control steps, error control, etc
TCP protocol------------------------------
Transmission control protocol is a connection oriented protocol, which is similar to calling
Establish connection = > communicate = > disconnect and use "three handshakes" before transmission

Three handshakes: client A, server B
It is mainly necessary to confirm the feasibility of their receiving capacity and sending capacity
The first time: A sends A message to B first to confirm whether the receiving and sending capabilities of himself and B are available (whether my transmission is obtained by B)
The second time: when B receives A's message, B knows that its receiving ability and A's sending ability are OK (B gets A's sending)
And send A message to A to confirm whether his sending ability and A's receiving ability are available (whether my sending is obtained by A)
The third time: A receives the message from B
Then you know that your sending ability and receiving ability are OK, and that B's sending ability and receiving ability are OK (my sending has been obtained by B and responded to me)
And send a message to B. both your receiving ability and your sending ability are OK (give a response)
Then, after receiving it, B confirms that the receiving and transmitting capabilities of itself and A are OK (confirming that A has been sent by B)
Then you can communicate
Examples can also be used to illustrate
For example: you wave to your sister first. When she sees you wave to herself, she nods to you and squeezes out a smile (your sending is received by her sister)
When you see your sister smiling, you confirm that she has successfully identified herself
But my sister was a little embarrassed. She looked downstairs and upstairs. Is it possible that you are looking at someone else? She also needs to confirm
The sister also waved to you (did you get the sending of the sister)
When you see your sister waving to you, you know that the other party is looking for your confirmation, so you nod and squeeze out a smile
You know, you and your sister can send and receive
After seeing each other's smile, the sister confirms that you are saying hello to yourself (confirm that you have received the message from the sister)
Sister knows, sister and you can send and receive
That is, the first and second handshakes confirm that A's sending and receiving are correct
The second and third handshakes confirm that B's sending and receiving are correct
The second handshake can be regarded as two handshakes, i.e. a - > b, B - > A, and a confirms that it is B (confirming that the receiving and sending capabilities of a can be)
Then B - > A, a - > b, B confirms that a sends a message to him (confirm that B's receiving and sending ability is OK)
That is, these three handshakes can be regarded as four handshakes, but the middle two are merged together
Client: in the web, it exists as a request object and sends the request to the server for processing
Server: as the name suggests, it is a service. The request sent by the client is handed over to the server for processing. It exists as a response object. After the server completes processing, it is fed back to the client
Generally, when we visit a website, the client (browser, app) sends a request, and then the other server (sina,sohu) responds
The result is to return the page path to us, and then we see the web page according to the path
In the whole process of communication, the connection is maintained in the whole process to form a data transmission channel
It ensures the reliability and order of data transmission
It is a full duplex byte stream communication mode, which can transmit a large amount of data
After transmission, the established connection needs to be released, and the efficiency of sending data is relatively low
UDP protocol------------------------------
User datagram protocol is a non connection oriented protocol, similar to letter writing
In the whole process of communication, there is no need to maintain a connection. In fact, there is no need to establish a connection
The reliability and order of data transmission are not guaranteed
It is a full duplex datagram communication mode, and the size of each datagram is limited to 64K
After sending data, there is no need to release resources, the overhead is small, the efficiency of sending data is relatively high and the speed is fast
Three handshakes to ensure the reliability of the connection
Wave four times and disconnect

Four wave understanding: client A, server B
First wave: A sends A message to B. I'm going to disconnect
Second wave: B is ready to disconnect after receiving the message from A
The third wave: B sends A message to A and I disconnect
The fourth wave: A sends A message to B, I see
//Bottom operation of three handshakes and four waves
//Three handshakes
First handshake:Client send SYN package(seq=x)Enter the server and SYN_SEND)(Request connection)Status, waiting for server confirmation
The Second Handshake :Server received SYN Package, the customer must be confirmed ack=x+1,Also send one yourself SYN package(seq=y),Namely SYN+ACK package
The server enters SYN_RECV(Semi connection)state
Third handshake:Client received from server SYN+ACK Package, send confirmation package to the server ack=y+1,After the package is sent, the client and server enter
ESTABLISHED(Connection established)Status, complete three handshakes
SYN Message, seq Initial serial number, ack Confirmation number, ACK Confirmation message segment
seq As long as the message is sent, it will be initialized once, and if it is sent many times, it will be added with 1
If the client sends it once, join seq by x,So next time seq Just for x+1(It can also be expressed in other letters, but it can only be expressed. In fact, add 1)
and ack Will be received seq+1,To confirm the receipt to the other party, and prompt that all data of the last time has been successfully received
ACK The message segment can carry data. If it does not carry data, the serial number will not be consumed. If it is 1, the connection is confirmed
SYN=1,ACK=1 Explanation of
The original computer is valid and invalid through 0 and 1, which only means that the package is confirmed to be valid
SYN=1,SYN Package valid
ACK=0,ACK Invalid package, ACK It just means that the package doesn't exist
Namely know SYN It just includes many things, such as seq Wait, and ACK It also includes a lot of things, such as ack
So you usually find SYN and ACK All 1
//Four waves
First wave:Client take FIN Set to 1, serial number seq=M,Send to Server
get into FIN_WAIT_1(Socket closed, closing connection[send out FIN,Not received ACK I didn't get it either FIN])state
Second wave:Server Upon receipt, we will ACK Set to 1, ack=M+1,Respond to Client
get into CLOSE_WAIT(The remote socket has been closed:Waiting to close this socket[Received by the passive Closing Party FIN])state
Client After receiving the response
get into FIN_WAIT_2(Socket closed, waiting for remote socket to close[stay FIN_WAIT_1 Received and sent in status FIN Corresponding ACK])state
Third wave:Server After all data transfers are completed, the Fin Set to 1, seq=N,Send to Client get into
LAST_ACK(Remote socket closed, waiting for local socket close confirmation[Passive party in CLOSE_WAIT Send in status FIN])state
Fourth wave:Client After receiving,take ACK Set to 1, ack=N+1,Respond to Server
get into TIME_WAIT(This socket has been closed and is waiting for the remote socket to be transferred[FIN,ACK,FIN,ACK It's all over
This is the last state of the active party after 2 MSL Become after time CLOSED state])Status, waiting 2 MSL after
get into CLOSED(This socket is not used[netstat Unable to display closed state])state
Server Upon receipt, enter CLOSED state
//For three handshakes
The client and server should be connected before communication,"3 Second handshake"The function of is that both parties can make it clear that their receiving and sending capacity and that of the other party are normal
First handshake:The client sends the network packet and the server receives it
In this way, the server can draw a conclusion:The sending capacity of the client and the receiving capacity of the server are normal
The Second Handshake :The server sends out the contract, and the client receives it
So the client can draw a conclusion:The receiving and sending capabilities of the server and the receiving and sending capabilities of the client are normal
From the perspective of the client, I received the response packet sent by the server, indicating that the server received the network packet I sent when I shook hands for the first time
And successfully sent the response packet, which indicates that the receiving and sending ability of the server is normal
On the other hand, I received the response packet from the server
It shows that the network packet I sent for the first time successfully arrived at the server. In this way, my own sending and receiving ability is also normal
Third handshake:Client contract, server received
In this way, the server can draw a conclusion:The receiving and sending capabilities of the client and the sending and receiving capabilities of the server are normal
The ability of the client to send and receive handshakes after the first handshake is not known by the server
In the third handshake, the server receives the response of the client to the second handshake
From the perspective of the server, I sent the response data during the second handshake, and the client received it
Therefore, my sending ability is normal. The receiving capacity of the client is also normal
//After the above three handshakes, both the client and the server confirm that their receiving and sending capabilities are normal. Then you can communicate normally
//As can be seen from the above process, at least three handshakes are required
//Two times can not reach the conclusion that both parties can draw the conclusion that their receiving and sending capabilities and those of the other party are normal
//For four waves
Actually TCP It provides the ability for one end of the connection to receive data from the other end after its transmission
among FIN It's also a bag, and there are many things, such as seq Etc., 1 means valid, 0 means invalid, and SYN and ACK Same package
The reason why there are four waves instead of three is that the data is completely read. You need to wait for the completion of data operation. For example, the second wave is to wait for the completion of data operation
IP address------------------------------
192.168.1.1 - is the login address of most routers. It is mainly configured with user name and password and Mac filtering
IP address is the unique address identification in the Internet. In essence, it is an integer composed of 32-bit binary, which is called IPv4
Of course, there are 128 bit binary integers, called IPv6. At present, the mainstream is IPv4
In daily life, the dotted decimal representation is used to describe the IP address, and the binary of each byte is transformed into a decimal integer
Different integers are separated by decimal points
For example: 0x01020304 = > 1.2.3.4
How to view IP addresses------------------------------
Windows system: use ipconfig or ipconfig/all command in dos window
Unix/linux system: use ifconfig or / sbin/ifconfig command in the terminal window
Special local loopback address (hostAddress): 127.0.0.1
Hostname: localhost
Port number------------------------------
IP address - you can locate a specific device
Port number - you can locate a specific process in the device
In essence, the port number is an integer composed of 16 bits binary, and the representation range is 0 ~ 65535. The port number between 0 ~ 1024 is usually occupied by the system
It is recommended that programming start from 1025
Special port------------------------------
HTTP:80
FTP:21
Oracle:1521
MySQL:3306
Tomcat:8080
Network programming needs to provide: IP address + port number, which is called network Socket: Socket
Programming model based on tcp protocol------------------------------
Introduction to C/S architecture:
In C/S mode, the client sends a service request to the server, and the server provides services after receiving the request
For example, in a hotel, the customer asks the waiter to order, and the waiter informs the chef of the order menu. The chef prepares the dishes according to the order menu and asks the waiter to bring them to the customer
This is a C/S working mode
If the hotel is regarded as a system, the waiter is the client and the cook is the server
This way of systematic division of labor and collaborative work is the working mode of C/S
Client part: it is exclusive to each user and is responsible for performing foreground functions
Server part: information and functions shared by multiple users, entertaining background services
Programming model------------------------------

The server:
Create an object of type ServerSocket and provide the port number
Wait for the connection request from the client and call the accept() method
Communication using input / output streams
Close Socket
client:
Create an object of Socket type and provide the IP address and port number of the server
Communication using input / output streams
Close Socket
ServerSocket class------------------------------
public class ServerSocket
extends Object
implements Closeable
java. net. The ServerSocket class is mainly used to describe server socket information (large row)
Common methods------------------------------
ServerSocket(int port),Construct the object according to the port number specified by the parameter
Socket accept(),Listen and receive connection requests to this socket
void close(),Used to close the socket
Socket class------------------------------
public class Socket
extends Object
implements Closeable
//Closeable is a data source or target that can be closed. Calling the close method can release the resources saved by the object (such as opening a file)
java.net.Socket class is mainly used to describe the client socket. It is the endpoint (small socket) of communication between two machines
Common methods------------------------------
Socket(String host, int port),Constructs an object based on the specified host name and port
InputStream getInputStream(),Used to get the input stream of the current socket
OutputStream getOutputStream(),Used to get the output stream of the current socket
void close(),Used to close the socket
Precautions------------------------------
The client Socket corresponds to the server Socket and contains input and output streams
Socket of client Getinputstream() connects to the server socket getOutputStream()
Socket of client Getoutputstream() connects to the server socket getInputStream()
package com.lagou.task19;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerStringTest {
public static void main(String[] args) {
ServerSocket ss = null;
Socket s = null;
try {
// 1. Create an object of ServerSocket type and provide the port number
//ServerSocket(int port) constructs an object according to the port number specified by the parameter
ss = new ServerSocket(8888);
// 2. Wait for the connection request from the client and call the accept method
while(true) {
System.out.println("Waiting for connection request from client...");
// When there is no client connection, the server blocks the call of the accept method
//Socket accept(), listens and receives connection requests to this socket
//You can receive the connection from the Socket client. If there is no loop, there will be nothing to receive the connection
//Therefore, when other clients connect, they need to loop, that is, multiple accept methods to receive
s = ss.accept();
//s.getInetAddress() gets the address of the client
System.out.println("client" + s.getInetAddress() + "Connection succeeded!");
// Whenever a client is successfully connected, a new thread needs to be started to serve it
//The reason for this is that the accept guarantees the execution of the loop, if not
//Since main is a thread, the accept method cannot be run when there is an infinite loop elsewhere in accept
new ServerThread(s).start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 4. Close the Socket and release relevant resources
if (null != ss) {
try {
//void close(), used to close the socket
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
package com.lagou.task19;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
public class ClientStringTest {
public static void main(String[] args) {
Socket s = null;
PrintStream ps = null;
Scanner sc = null;
BufferedReader br = null;
try {
// 1. Create an object of Socket type and provide the host name and port number of the server
//Socket(String host, int port), which constructs objects according to the specified host name and port
s = new Socket("127.0.0.1", 8888);
System.out.println("Successfully connected to the server!");
// 2. Use input / output stream for communication
sc = new Scanner(System.in);
//InputStream getInputStream(), used to get the input stream of the current socket
//OutputStream getOutputStream(), used to obtain the output stream of the current socket
ps = new PrintStream(s.getOutputStream());
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
while(true) {
//Thread.sleep(10000);
// The content sent by the client is input by the user from the keyboard
System.out.println("Please enter the data content to send:");
String str1 = sc.next();
// Realize that the client sends the string content "hello" to the server
//ps.println("hello");
ps.println(str1);
System.out.println("The client sent the data content successfully!");
// When the data content sent is "bye", the chat ends
if ("bye".equalsIgnoreCase(str1)) {
System.out.println("The chat is over!");
break;
}
// Receive the string content sent by the server and print it
//You must read \ n or \ r to stop
//Therefore, blocking will occur. It is mainly used for Socket network programming to block and wait for input
String str2 = br.readLine();
System.out.println("The message sent back by the server is:" + str2);
}
} catch (IOException /*| InterruptedException*/ e) {
//Two | when you judge that the first one is true, the latter one will not judge, while the other one will judge
//Two & & when you judge the first one as false, the latter one will not judge, while the other & will judge
//But they are shift operators between numbers, not between judgments
e.printStackTrace();
} finally {
// 3. Close the Socket and release relevant resources
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != ps) {
ps.close();
}
if (null != sc) {
sc.close();
}
if (null != s) {
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
package com.lagou.task19;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.Socket;
public class ServerThread extends Thread {
private Socket s;
public ServerThread(Socket s) {
this.s = s;
}
@Override
public void run() {
BufferedReader br = null;
PrintStream ps = null;
try {
// 3. Use input / output stream for communication
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
ps = new PrintStream(s.getOutputStream());
while(true) {
// Receive and print the string content sent by the client
// When no data is sent, the following methods will form a block
String s1 = br.readLine();
InetAddress inetAddress = s.getInetAddress();
System.out.println("client" + inetAddress + "The content of the string sent is:" + s1);
// When the content sent by the client is "bye", the chat ends
if ("bye".equalsIgnoreCase(s1)) {
System.out.println("client" + inetAddress + "Offline!");
break;
}
// Realize that the server sends back the string content "I received!" to the client
ps.println("I received!");
System.out.println("The server sent data successfully!");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != ps) {
ps.close();
}
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != s) {
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Programming model based on udp protocol------------------------------
Programming model
Receiver:
Create an object of DatagramSocket type and provide the port number
Create an object of DatagramPacket type and provide a buffer
The data content is stored in the Packet through Socket, and the receive method is called.
Close Socket
Sender:
When creating an object of DatagramSocket type, the port number is not written because the port will be specified when sending
Create an object of DatagramPacket type and provide the communication address of the receiver
Send the data content in the Packet through the Socket and call the send method
Close Socket
Datagram socket class------------------------------
public class DatagramSocket
extends Object
implements Closeable
//Closeable is a data source or target that can be closed. Calling the close method can release the resources saved by the object (such as opening a file)
java.net.DatagramSocket class is mainly used to describe the socket (post office) that sends and receives datagrams. In other words, this class is the sending or receiving point of package delivery service
Common methods------------------------------
DatagramSocket(),Construct objects with no parameters
DatagramSocket(int port),Construct the object according to the port number specified by the parameter
void receive(DatagramPacket p),It is used to store the received datagram in the location specified by the parameter. If it is not received, it will be blocked, and accept Similar method
void send(DatagramPacket p),Used to send the datagram specified by the parameter
void close(),close Socket And release relevant resources
Datagram packet class------------------------------
public final class DatagramPacket
extends Object
java. net. Datagram packet class is mainly used to describe datagram, which is used to realize connectionless package delivery service
Common methods------------------------------
DatagramPacket(byte[] buf, int length),Construct an object according to the array specified by the parameter, which is used to receive an object with a length of length Datagram for
If sent"hs",Receive one, then only h,From the front to the back, if you receive three, it will be greater than the length of the transmission, that is, all will be received, and there will be no other data
That is, it actually receives two
DatagramPacket(byte[] buf, int length, InetAddress address, int port),Construct an object by specifying an array of parameters
Send datagrams to the specified address and port, such as"hse",Send two, then only hs,From front to back
The above two are operations on arrays, that is, both the sent data and the received array are arrays, that is, after sending the data of the array, put the received data into the array
InetAddress getAddress(),Used to obtain the communication address of the sender or receiver
int getPort(),Used to obtain the port number of the sender or receiver
int getLength(),Used to obtain the length of sent data or received data
The address indicated above must be available, such as the local address
InetAddress class------------------------------
public class InetAddress
extends Object
implements Serializable
//Serializable, serializable interface
java.net.InetAddress class is mainly used to describe Internet communication address information
Common methods------------------------------
static InetAddress getLocalHost(),Used to obtain the communication address of the current host
static InetAddress getByName(String host),Obtain the communication address according to the host name specified by the parameter
package com.lagou.task19;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class ReceiveTest {
public static void main(String[] args) {
DatagramSocket ds = null;
try {
// 1. Create an object of DatagramSocket type and provide the port number
//Datagram socket (int port), which constructs the object according to the port number specified by the parameter
ds = new DatagramSocket(8888);
// 2. Create DatagramPacket type object and provide buffer
byte[] bArr = new byte[20];
//Datagram packet (byte [] buf, int length) constructs an object according to the array specified by the parameter
//Used to receive datagrams with length
DatagramPacket dp = new DatagramPacket(bArr, bArr.length);
// 3. Receive the data through the Socket, store the content in the Packet, and call the receive method
System.out.println("Waiting for data...");
//Void receive (datagram packet P) is used to receive datagrams and store them in the location specified by the parameter
ds.receive(dp);
System.out.println("The received data content is:" + new String(bArr, 0, dp.getLength()) + "!");
// Implement the string content "I received!" Send it back
byte[] bArr2 = "I received!".getBytes();
//DatagramPacket(byte[] buf, int length, InetAddress address, int port)
//Construct an object by specifying an array of parameters
//Sends datagrams to the specified address and port
//int getPort(), used to obtain the port number of the sender or receiver
//int getLength(), which is used to obtain the length of sent data or received data
DatagramPacket dp2 = new DatagramPacket(bArr2, bArr2.length, dp.getAddress(),
dp.getPort());
//Void send (datagram packet P) is used to send the datagram specified by the parameter
ds.send(dp2);
System.out.println("Sending back data succeeded!");
} catch (IOException e) {
e.printStackTrace();
} finally {
// 4. Close the Socket and release relevant resources
if (null != ds) {
ds.close();
}
}
}
}
package com.lagou.task19;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class SendTest {
public static void main(String[] args) {
DatagramSocket ds = null;
try {
// 1. Create DatagramSocket type object
ds = new DatagramSocket();
// 2. Create an object of datagram packet type and provide the communication address and port number of the receiver
byte[] bArr = "hello".getBytes();
//static InetAddress getLocalHost(), used to obtain the communication address of the current host
DatagramPacket dp = new DatagramPacket(bArr, bArr.length, InetAddress.getLocalHost(),
8888);
// 3. Send the Packet through the Socket and call the send method
ds.send(dp);
System.out.println("Sending data succeeded!");
// Receive the data content sent back
byte[] bArr2 = new byte[20];
DatagramPacket dp2 = new DatagramPacket(bArr2, bArr2.length);
ds.receive(dp2);
System.out.println("The received postback message is:" + new String(bArr2, 0, dp2.getLength()));
} catch (IOException e) {
e.printStackTrace();
} finally {
// 4. Close the Socket and release relevant resources
if (null != ds) {
ds.close();
}
}
}
}
For some classes, there is no close method because the class does not occupy resources. For example, the File class only represents the path and does not operate on the File
That is, there is basically a close method for operations that occupy some resources and make other operations inoperable
For both TCP and UDP, ports and addresses are required
However, TCP only needs the accpet method to get the client, and the data is transmitted by IO stream. After connection, it can be transmitted directly to each other, but it must be connected, that is, the accpet method is not blocked
It's like a telephone
UDP needs to send data to each other, and it is specific data. It is stored in data, referred to as buffer for short. It is transmitted unilaterally. If it wants to transmit to each other, it needs buffer
As long as the address can be found, data can be sent. Instead of TCP, accpet must not be blocked, that is, it must be connected, just like writing a letter
Although the address and port are basically known in TCP and UDP, TCP has the possibility of connection failure, but a large amount of data can be generated after successful connection through the address and port
It only needs to disconnect, that is, release resources. Although the amount of UDP data is small, it is accurate and does not need to be connected to send, but directly send
Know the address and port of the other party, such as telephone connection (during the call, the process of connection), write a letter without connection (send information directly)
If TCP has no accpet method, the client will fail to connect, that is, it will confirm the connection of the server, so TCP connects through
Even if UDP does not have a receive method to receive, it will be sent out, that is, it will not confirm the situation of the other party, so UDP is not connected
URL class------------------------------
public final class URL
extends Object
implements Serializable
//Serializable, serializable interface
java. net. The URL (Uniform Resource Identifier) class is mainly used to represent a unified resource locator, that is, a pointer to "resources" on the world wide web
This resource can be a simple file or directory, or a reference to a complex object, such as a query to a database or search engine
You can access the network resources on the world wide web through the URL. The most common sites are www and ftp sites. The browser can find the corresponding resources on the network by parsing the given URL
The basic structure of the URL is as follows: < transport protocol > / / < host name >: < port number > / < resource address >
Common methods------------------------------
URL(String spec),Construct the object according to the string information specified by the parameter
String getProtocol(),Get agreement name
String getHost(),Get host name
int getPort(),Get port number
String getPath(),Get path information
String getFile(),Get file name
URLConnection openConnection(),obtain URLConnection Instance of class
URLConnection class------------------------------
public abstract class URLConnection
extends Object
java. net. The urlconnection class is an abstract class that represents the superclass of all classes of communication links between applications and URL s
The main implementation classes include the HttpURLConnection class that supports the unique functions of HTTP
Common methods of HttpURLConnection class------------------------------
InputStream getInputStream(),Get input stream
void disconnect(),Disconnect
package com.lagou.task19;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class URLTest {
public static void main(String[] args) {
try {
// 1. Use the string specified by the parameter to construct the object
//URL(String spec), which constructs the object according to the string information specified by the parameter
URL url = new URL("https://www.lagou.com / "); / / where s of https stands for security
//That is, http is less secure, while https is more secure
// 2. Obtain relevant information and print it out
//String getProtocol(), get the protocol name
System.out.println("The obtained protocol name is:" + url.getProtocol());
//String getHost(), get the host name
System.out.println("The obtained host name is:" + url.getHost());
//int getPort(), get the port number
System.out.println("The obtained port number is:" + url.getPort());
//Print - 1 description not obtained
// 3. Establish a connection, read relevant information and print it out
//URLConnection openConnection(), get the instance of URLConnection class
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
//Because the buffer stream can read multiple data at one time, there is a method to read multiple data
String str = null;
while ((str = br.readLine()) != null) {
System.out.println(str);
}
br.close();
// Disconnect
urlConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The number is:" + url.getPort());
//Print - 1 description not obtained
// 3. Establish a connection, read relevant information and print it out
//URLConnection openConnection(), get the instance of URLConnection class
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
//Because the buffer stream can read multiple data at one time, there is a method to read multiple data
String str = null;
while ((str = br.readLine()) != null) {
System.out.println(str);
}
br.close();
// Disconnect
urlConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}