Use of the InternetAccess class
An overview,
-
Computer Network:
- The distribution of computers in different geographical areas and special external equipment with communication lines into a large, powerful network system, so that a large number of computers can easily communicate information to share hardware, software, data information and other resources.
-
The purpose of network programming: directly or indirectly through the network protocol and other computers to achieve data exchange, communication
-
Two problems need to be solved to achieve network communication:
- How to accurately locate one or more hosts on the network; Locate a specific application on the host
- How to reliably and efficiently transfer data after finding the host
2. Network communication elements
- Solve problem 1: IP and port number
- Solution 2: Provide network communication protocol: TCP/IP reference model (application layer, Transport layer, network layer, physical + data link layer)
Network communication protocol
The communication process
3. Communication element 1: IP address and port number
3.1 Understanding IP
-
IP: Uniquely identifies a computer (communication entity) on the Internet
-
Use the InetAddress class to represent IP in Java
-
IP address category: IPv4 and IPv6. World Wide Web and Local Area Networks
-
Domain name: The domain name is resolved to an IP address using the DNS server, for example, www.baidu.com www.mi.com www.jd.com
-
Domain name resolution: Domain names are easy to remember. When you enter the domain name of a host when connecting to the network, the domain name server (DNS) converts the domain name into an IP address so that you can establish a connection with the host.
-
Local loop address: 127.0.0.1 corresponds to localhost
3.2 Port Number:
Used to identify the process that is running on the computer.
- Requirements: Different processes have different port numbers
- Range: The value is a 16-bit integer ranging from 0 to 65535.
- Classification:
- Recognized ports: 0 to 1023. These ports are used by predefined services, such as HTTP port 80, FTP port 21, and TeInet port 23.
- Registered port: 1024 to 49151. Assigned to user processes or applications. (For example, Tomcat occupies port 8080, MSQL occupies port 3306, and Oracle occupies port 1521.)
- Dynamic private port: 49152 to 65535.
3.3 InetAddress class
An object of this class represents a specific IP address
3.2.1 instantiation
getByName(String host)
/getLocalHost()
3.2.2 Common methods
getHostName()
/ getHostAddress()
public class InetAddressTest {
public static void main(String[] args) {
try {
//File file = new File("hello.txt");
InetAddress inet1 = InetAddress.getByName("192.168.10.14");
System.out.println(inet1);
InetAddress inet2 = InetAddress.getByName("www.baidu.com");
System.out.println(inet2);
InetAddress inet3 = InetAddress.getByName("127.0.0.1");
System.out.println(inet3);
// Obtain the local IP address
InetAddress inet4 = InetAddress.getLocalHost();
System.out.println(inet4);
//getHostName()
System.out.println(inet2.getHostName());
//getHostAddress()
System.out.println(inet2.getHostAddress());
} catch(UnknownHostException e) { e.printStackTrace(); }}Copy the code
4. Communication element 2: network communication protocol
4.1 Layered Model
4.2 Differences between TCP and UDP
TCP protocol:
-
Before using TCP, you need to establish a TCP connection to form a data transmission channel
-
Before transmission, use “three handshake” mode, point – to – point communication, is reliable
-
TCP is used to communicate with two application processes: the client and the server.
-
Large amounts of data can be transferred in the connection
-
After transmission, existing connections need to be released, which is inefficient
UDP protocol:
-
Encapsulate data, source, and destination into packets without establishing a connection
-
The size of each datagram is limited to 64K
-
Sending is unreliable regardless of whether the other party is ready or not, and the receiver does not acknowledge receipt
-
You can broadcast it
-
When data is sent, no resources are released, and the cost is low and the speed is fast
4.3 TCP Three-way handshake and four-way wave
5. Socket
The combination of port number and IP address yields a network Socket: Socket
-
Developing network applications using sockets has long been so widely adopted that it has become the de facto standard.
-
IP addresses and port numbers with unique identifiers on the network are combined to form a uniquely identifiable identifier socket.
-
Both ends of communication must have sockets, which are the endpoints of communication between two machines.
-
Network communication is actually communication between sockets.
-
A Socket allows an application to treat a network connection as a stream, with data transferred between two sockets via IO.
-
Generally, the application program that initiates communication actively belongs to the client, while the application program waiting for communication request belongs to the server
-
Classification of the Socket
- Flow socket (
stream socket
) : Provides a reliable byte stream service using TCP - Datagram socket (
datagram socket
) : provides “best efforts” datagram service using UDP
- Flow socket (
TCP network programming
Java language Socket based programming is divided into client and server
Socket communication model based on TCP
1. TCP programming based on Socke
1.1 Working process of client Socket
-
Creating a Socket: Constructs an Sσcket object based on the IP address or port number of the specified server. If the server responds, a communication line is established between the client and the server. If the connection fails, an exception occurs.
-
Open the input and output streams connected to the Socket: use the getInputstream() method to get the input stream and the getOutputStream() method to get the output stream for data transfer
-
Read/write the Socket according to a certain protocol: read the information put into the line by the server through the input stream (but cannot read the information put into the line by itself), and write the information into the thread through the output stream
-
Disable the Socket: Disconnects the client from the server and releases the cable
Description:
-
The client program can use the Socket class to create objects, and at the same time, it will automatically initiate a connection to the server.
-
The Socket constructor is:
Socket(String host, int port) throws UnknownHostException
.EXCeption
: To the server (domain name ishost
, the port number isport
)TCP
Connect, if successful, createSocket
Object, otherwise an exception is thrown.Socket(InetAddress Address, int port)throws IOException
: according to theInetAddress
Object represented byIP
Address and port numberport
A connection
-
The client establishes a socketAtClient object by making a socket connection request to the server
1.2 Working process of server-side Socket:
-
Call ServerSocket(int Port) : Creates a server-side socket and binds it to the specified port. Used to listen for client requests.
-
Call accept0() : listens for connection requests, accepts the connection if the client requests it, and returns a communication socket object.
-
Call getOutputStream() and getInputStream() of the Socket class object: get the output stream and input stream, and start sending and receiving network data.
-
Close ServerSocket and Socket objects: The client access is complete and the communication Socket is closed.
Description:
-
The ServerSocket object is responsible for waiting for a client request to establish a socket connection, similar to a salesman in a post office window. That is, the Server must set up a Server Socket object waiting for a client to request a Socket connection.
-
The accept() method returns a Socket object
1.3 Code Examples
Example 1: The client sends information to the server, and the server displays the data on the console
public class TCPTest1 {
/ / the client
@Test
public void client(a) {
Socket socket = null;
OutputStream os = null;
try {
//1. Create a Socket object and specify the IP address and port number of the server
InetAddress inet = InetAddress.getByName("192.168.14.100");
socket = new Socket(inet,8899);
//2. Get an output stream for output data
os = socket.getOutputStream();
//3. Write out data
os.write("Hello, this is client MM.".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
//4. Resource shutdown
if(os ! =null) {try {
os.close();
} catch(IOException e) { e.printStackTrace(); }}if(socket ! =null) {try {
socket.close();
} catch(IOException e) { e.printStackTrace(); }}}}/ / the server
@Test
public void server(a) {
ServerSocket ss = null;
Socket socket = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
//1. Create a ServerSocket on the server and specify its own port number
ss = new ServerSocket(8899);
2. Call Accept () to receive the socket from the client
socket = ss.accept();
//3. Get the input stream
is = socket.getInputStream();
// It is not recommended to write this, it may be garbled
// byte[] buffer = new byte[1024];
// int len;
// while((len = is.read(buffer)) ! = 1) {
// String str = new String(buffer,0,len);
// System.out.print(str);
/ /}
//4. Read the data in the input stream
baos = new ByteArrayOutputStream();
byte[] buffer = new byte[5];
int len;
while((len = is.read(buffer)) ! = -1){
baos.write(buffer,0,len);
}
System.out.println(baos.toString());
System.out.println("Received from:" + socket.getInetAddress().getHostAddress() + "The data");
} catch (IOException e) {
e.printStackTrace();
} finally {
if(baos ! =null) {//5. Close the resource
try {
baos.close();
} catch(IOException e) { e.printStackTrace(); }}if(is ! =null) {try {
is.close();
} catch(IOException e) { e.printStackTrace(); }}if(socket ! =null) {try {
socket.close();
} catch(IOException e) { e.printStackTrace(); }}if(ss ! =null) {try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Copy the code
Example 2: The client sends a file to the server, and the server saves the file locally.
public class TCPTest2 {
/* Try-catch-finally should be used to handle */
@Test
public void client(a) throws IOException {
/ / 1.
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9090);
/ / 2.
OutputStream os = socket.getOutputStream();
/ / 3.
FileInputStream fis = new FileInputStream(new File("beauty.jpg"));
/ / 4.
byte[] buffer = new byte[1024];
int len;
while((len = fis.read(buffer)) ! = -1){
os.write(buffer,0,len);
}
/ / 5.
fis.close();
os.close();
socket.close();
}
/* Try-catch-finally should be used to handle */
@Test
public void server(a) throws IOException {
/ / 1.
ServerSocket ss = new ServerSocket(9090);
/ / 2.
Socket socket = ss.accept();
/ / 3.
InputStream is = socket.getInputStream();
/ / 4.
FileOutputStream fos = new FileOutputStream(new File("beauty1.jpg"));
/ / 5.
byte[] buffer = new byte[1024];
int len;
while((len = is.read(buffer)) ! = -1){
fos.write(buffer,0,len);
}
/ / 6.fos.close(); is.close(); socket.close(); ss.close(); }}Copy the code
Example 3: The client sends a file to the server, and the server saves the file locally. And returns a message “Sent successfully” to the client.
public class TCPTest3 {
/* Try-catch-finally should be used to handle */
@Test
public void client(a) throws IOException {
/ / 1.
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9090);
/ / 2.
OutputStream os = socket.getOutputStream();
/ / 3.
FileInputStream fis = new FileInputStream(new File("beauty.jpg"));
/ / 4.
byte[] buffer = new byte[1024];
int len;
while((len = fis.read(buffer)) ! = -1){
os.write(buffer,0,len);
}
// Close the output of data
socket.shutdownOutput();
//5. Receive data from the server and display it to the console
InputStream is = socket.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] bufferr = new byte[20];
int len1;
while((len1 = is.read(buffer)) ! = -1){
baos.write(buffer,0,len1);
}
System.out.println(baos.toString());
/ / 6.
fis.close();
os.close();
socket.close();
baos.close();
}
/* Try-catch-finally should be used to handle */
@Test
public void server(a) throws IOException {
/ / 1.
ServerSocket ss = new ServerSocket(9090);
/ / 2.
Socket socket = ss.accept();
/ / 3.
InputStream is = socket.getInputStream();
/ / 4.
FileOutputStream fos = new FileOutputStream(new File("beauty2.jpg"));
/ / 5.
byte[] buffer = new byte[1024];
int len;
while((len = is.read(buffer)) ! = -1){
fos.write(buffer,0,len);
}
System.out.println("Picture transfer completed");
//6. The server sends feedback to the client
OutputStream os = socket.getOutputStream();
os.write("Hello, beauty, I have received the photo, very beautiful!".getBytes());
/ / 7.fos.close(); is.close(); socket.close(); ss.close(); os.close(); }}Copy the code
UDP network programming
1. A brief introduction
-
Class DatagramSocket and DatagramPacket realize network program based on UDP protocol.
-
UDP datagramsockets are used to send and receive UDP datagramsockets. The system does not guarantee that UDP datagramsockets will be safely delivered to their destination or when they will arrive.
-
The DatagramPacket object encapsulates a UDP datagram, which contains the IP address and port number of the sender and the IP address and port number of the receiver
-
Each UDP datagram provides complete address information, so there is no need to establish a connection between the sender and receiver. It’s like sending a package.
2. Common DatagramSocket methods
3. Use the DatagramSocket class
Process:
-
DatagramSocket and DatagramPacket
-
Establish sender and receiver
-
Setting up packets
-
Call the send and receive methods of the Socket
-
Close the Socket
Note: the sender and the receiver are two separate running programs
Code examples:
public class UDPTest {
/ / the sender
@Test
public void sender(a) throws IOException {
DatagramSocket socket = new DatagramSocket();
String str = "I'm a UDP missile.";
byte[] data = str.getBytes();
InetAddress inet = InetAddress.getLocalHost();
DatagramPacket packet = new DatagramPacket(data,0,data.length,inet,9090);
socket.send(packet);
socket.close();
}
/ / the receiving end
@Test
public void receiver(a) throws IOException {
DatagramSocket socket = new DatagramSocket(9090);
byte[] buffer = new byte[100];
DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
socket.receive(packet);
System.out.println(new String(packet.getData(),0,packet.getLength())); socket.close(); }}Copy the code
5. URL programming
-
Uniform Resource Locator (URL) : a Uniform Resource Locator (URL) that indicates the address of a Resource on the Internet.
-
It is a concrete URI that can be used to identify a resource and also indicate how to locate the resource.
-
Through urls we can access all kinds of network resources on the Internet, such as the most common WWW, FTP sites. Browsers can find files or other resources on the network by parsing a given URL
-
The basic structure of the URL consists of five parts: < transport protocol > : //< host name > : < port number >/< file name ># fragment name? The list of parameters
For example: http://192.168.1.100:8080/helloworld/indexjsp#a? username=shkstart&password=123
# Segment name: that is, the anchor point, such as reading a novel, directly to the chapter
Parameter list format: Parameter name = Parameter Value & Parameter name = Parameter Value…
1. The URL class
1.1 the constructor
To represent urls, class urls are implemented in Java.net. We can initialize a URL object with the following constructor
-
Public URL(String spec) : A URL object can be constructed from a String representing the URL address. For example, URL URL = new URL (“[http://www.baidu.com/](http://www.baidu.com/)”);
-
Public URL(URL Context,String spec) : Constructs a URL object from a base URL and a relative URL
For example, URL downloadeUrl = new URL(URL,”download.html”);
-
public URL(String protocol,String host,String file);
` ` for example: the new URL (” HTTP “, “[www.baidu.com] (http://www.baidu.com),” 80, “the download. HTML”);
-
public URL(String protocol,String host,int port,String file);
For example: the new URL (” HTTP “, “[www.baidu.com] (http://www.baidu.com),” 80, “the download. HTML”);
Note: The constructors of URL classes declare that they throw a non-runtime exception, which must be handled, usually with a try-catch statement.
1.2 methods
public String getProtocol()
To get theURL
The agreement ofpublic String getHost()
To get theURL
The host namepublic String getPort()
To get theURL
The port numberpublic String getPath()
To get theURL
File path topublic String getFile()
To get theURL
The name of the filepublic String getQuery()
To get theURL
The query name
Code sample
public class URLTest {
public static void main(String[] args) {
try {
URL url = new URL("http://localhost:8080/examples/beauty.jpg?username=Tom");
// public String getProtocol() gets the protocol name of the URL
System.out.println(url.getProtocol());
// public String getHost() gets the host name of the URL
System.out.println(url.getHost());
// public String getPort() gets the port number of the URL
System.out.println(url.getPort());
// public String getPath() gets the file path of the URL
System.out.println(url.getPath());
// public String getFile() gets the file name of the URL
System.out.println(url.getFile());
// public String getQuery() gets the query name of the URL
System.out.println(url.getQuery());
} catch(MalformedURLException e) { e.printStackTrace(); }}}Copy the code
Example: Download via URL
public class URLTest1 {
public static void main(String[] args) {
HttpURLConnection urlConnection = null;
InputStream is = null;
FileOutputStream fos = null;
try {
URL url = new URL("http://localhost:8080/examples/beauty.jpg");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
is = urlConnection.getInputStream();
fos = new FileOutputStream("beauty3.jpg");
byte[] buffer = new byte[1024];
int len;
while((len = is.read(buffer)) ! = -1){
fos.write(buffer,0,len);
}
System.out.println("Download completed");
} catch (IOException e) {
e.printStackTrace();
} finally {
// Close the resource
if(is ! =null) {try {
is.close();
} catch(IOException e) { e.printStackTrace(); }}if(fos ! =null) {try {
fos.close();
} catch(IOException e) { e.printStackTrace(); }}if(urlConnection ! =null){ urlConnection.disconnect(); }}}}Copy the code