Textbook content summary
- Master the usage of
URL class URL class constructor:
public URL(String spec) throws MaldormedURLException This constructor initializes a URL object with a string
public URL (String protocol,String host,String file) throws MaldormedURLException The protocol used by this constructor , the address and resource are specified by the parameters protocol, host and file respectively.
The protocol in the above url object is the http protocol.
Read the resource in the URL: Call the InputStream openStresm() method to return an input stream. - Master
the InetAddress class Representation method of address: domain name and IP address
Representation method of address: The InetAddress class object in the java.net package contains the domain name or IP address of a host address.
Get address
Get the address of the host on the InetAddress: getByName(String s) gets a domain name or IP address; getHostName() gets the domain name contained in the InetAddress object; getHostAddress() gets the IP address contained in the InetAddress object.
Get the address of the local machine: getLocalHost() gets an InetAddress object, which contains the domain name and IP address of the local machine. - Master the use of sockets
Overview The
port is specified as 0~65535
0~1023 is pre-occupied
Client socket
Socket (String host, iint port), the parameter host is the IP address of the server, and port is a port number.
IOException may occur in the method of establishing a socket object, so use the try-catch method
ServerSocket object and server-side socket
construction method: (int port), port is a port. port must be the same as the port number the client calls. Also use the try-catch method.
After the connection is established, the server socket object calls the getInetAddress() method to obtain an InetAddress object, which contains the client's IP address and domain name.
After the two parties have finished communicating, the socket should use the close() method to close the socket connection.
Using multi-threading technology
, a socket object can be created by using the Socket() constructor without parameters of the Socket class, which calls public void connect(Socket Address endpoint) throws IOException to request connection with the server specified by the parameter SocketAddress.
In socket communication, there are two basic principles: (1) The server should start a dedicated thread and connect with the client's socket in this thread. (2) Since the input stream of the socket may block when reading the message, both the client and the server need to read the information in a separate thread.
Master the UDP datagram
The basic mode of communication based on UDP
Pack data into data packets, and then send the data packets to the destination
Receive the incoming data packet, and then view the content in the
data packet Send the data packet
Receive the data packet
Learn java remote call
code link
Code screenshot