JAVA Network Programming
The network can achieve resource sharing and communication, and java Network functions can be implemented using the java.net package. The java.net package provides a powerful foundation for the network.
Java.net package
Socket-related classes
Web-related classes
Network
Implement the communication system of the resource sharing and communication connection terminal system (host)
Network Adapter
A computer connects a network interface card through a cable NIC is used to connect a computer to a cable, also known as a network adapter.
Communication rules for computers in the Network
Common protocols 1. Hypertext Transfer protocol HTTP 2. File Transfer Protocol FTP 3. Simple Mail Transfer Protocol SMTP 4. network news transmission protocol NNTP
Port
Common port Telnet protocol for inter-program communication 23 Simple Mail transmission protocol 25 text transmission protocol 21 Hypertext Transfer Protocol 80
Client/Server mode
Also known as the smart server/smart client architecture. servers and clients share computing 1. the client requests the service from another computer. advantages of the computer used by the server to process client requests: the server and client share the work server can serve multiple front-end clients simultaneously to access the server
IP and DNS
Each computer connected to the network with an IP address is a unique 32-digit number, the four numbers separated by dots include the network ID and host ID. The network classes include A, B, C, and D. the Domain Name System Maps specific IP addresses to string ing, which is maintained by the Domain Name Server System.
Java.net package
Available Classes 1. InetAddress2.Socket, ServerSocket, and SocketImpl3.DatagramPacket and DatagramSocket4.URL, URLConnection, and URLEncoder
Socket
Is an Internet communication endpoint associated with the host address and port address. The client establishes a connection with the server through a socket and communicates with the server. 1.TCP/ IP socket provides message confirmation for sending data of any attribute., error detection, error recovery, and other services 2. relatively unreliable UDP socket
InetAddress
The encapsulation IP address and DNS factory method are used to create instance 1. InetAddress getLocalHost () 2. InetAddress getByName (String HostName)
Package com. lizhenhua. test;
Import java.net. InetAddress;
Import java.net. UnknownHostException;
Public class InetAddressTest {
Public static void main (String [] args ){
Try {
// Obtain the local IP Address
InetAddress address = InetAddress. getLocalHost ();
System. out. println ("local IP address:" + address );
// Obtain the host address InetAddress add2 = InetAddress of the corresponding service through DNS resolution based on the domain name. getByName ("www.163.com"); System. out. println ("Netease server host:" + add2); // obtain the host address (if this IP address is available on the network) based on the IP address of the string representation. InetAddress add3 = InetAddress. getByName ("192.168.0.22"); System. out. println ("host whose IP address is 192.168.0.22:" + add3); // obtain the corresponding host address based on the machine name (if the machine name exists on the network) InetAddress add4 = InetAddress. getByName (add3.getHostName (); System. out. println ("local host name of the machine :" + Add4); // print the parameters related to the local IP address // return the IP address String HostAddress = address. getHostAddress (); // obtain the local host name. String hostName = address. getHostName (); // returns the original IP address byte [] IP = address. getAddress (); // if the host name is specified, the service returns an array composed of its IP addresses based on the name configured on the system. InetAddress [] baidus = InetAddress. getAllByName ("www.baidu.com"); // returns the InetAddress object when the original IP address is specified. // Obtain the local IP address object InetAddress localhost = InetAddress. getByAddress (IP); for (InetAddress inetAddress: baidus) {System. out. println ("IP Address:" + inetAddress. getHostAddress (); System. out. println ("host name corresponding to the IP Address:" + inetAddress. getHostName () ;}} catch (UnknownHostException e) {// TODO Auto-generated catch block e. printStackTrace ();}}
}
Local IP Address: PCOS-10271310/192.168.1.102
Netease server host: www.163.com/222.186.132.123
Host with IP address 192.168.0.22:/192.168.0.22
Local host name:/192.168.0.22
IP Address: 14.215.177.38
Host name corresponding to the IP Address: www.baidu.com
IP Address: 14.215.177.37
Host name corresponding to the IP Address: www.baidu.com
Socket
Establish a connection between the server and the client
Constructor
Socket(String hostName,int port)Socket(InetAddress a ,int port)
Available Methods
InetAddress getInetAddress()int getPort()int getLocalPort()
ServerSocket
The accept () method is used to wait for the client to trigger communication.
Constructor
ServerSocket (int port)
ServerSocket (int port, int maxqu)
Socket programming
Compile the server-side program:
Create a server Socket and bind it to the specified port. Call the accept method to listen for requests from the client. If the client sends a request, the client accepts the connection and returns the Socket ); call the getInputStream and getOutputStream methods of the Socket to obtain the input/output stream and start receiving and sending network data. Disable the communication Socket and the server Socket.
Compile the client program:
Create a Socket to send a request to the server's listening port;
After correctly connecting to the server, call the getInputStream and getOutputStream methods of the Socket to obtain the input/output stream and start receiving and sending network data;
Disable communication socket.
IO stream
The computer system processes all devices except the CPU and memory as files, including network terminals (NICS). After the two hosts establish a handshake connection through a socket, it is mainly used to receive and send data through input/output streams. In fact, most of network operations are performed on IO streams; in fact, the operating principle of the network port stream is similar to that of the disk file stream. for efficiency reasons, scoket uses byte streams, but in actual operations, bytes tend to cause inconvenience, therefore, we generally convert the byte stream into a bytes stream for operations.
For InputStream, use InputStreamReader to convert the stream into a bytes stream first;
Then, use BufferedReader to create a buffer to improve efficiency,
For example:
InputStream is = socket. getInputStream ();
InputStreamReader isr = new InputStreamReader (is );
BufferedReader in = new BufferedReader (isr );
Datagram
Communication is a message type. Two types of communication are available: the mongorampacket data container, which sends or receives the mongorampacket‑ramsocket. It is used to send or receive the mongorampacket constructor, mongoramsocket () mongoramsocket (int port) void receive (DatagramPacket p) void close () DatagramPacket serves as a data container class constructor DatagramPacket (byte [] data, int size) DatagramPacket (byte [] data, int size, inetAddress I, int port)
URL
The URL class of the resource file pointing to the Internet provides APIs to access the component protocol IP address of the Information URL on the Internet or the actual file path of the host name and port number. The URL constructor URL (String urlname) URL (String protocol, string hostname, int port, String path) URL (String protocol, String hostname, String path) the URLConnection abstract class is used to encapsulate the link of a Web object represented by a URL. It provides a method to learn more about remote resources. Available Methods: URLConnection openConnection * (String getContentType () long getLastModified () int getContentLength () URLEncoder converts a text string to a URL. The encode () method is provided. convert a space into a plus sign (+) 2. use % as the escape code and encode the special characters. The java.net package socket-related Web-related classes are summarized.
OSI: Open Systems InterConnection; Open System InterConnection. It is a layered model that divides the entire network into seven layers, so that computers in the network can exchange information with each other in a standardized manner, used for different devices but are interconnected.
1. Physical Layer
Detection of physical settings
2. Data Link Layer
Control communication between the network layer and the physical layer
3. Network Layer
Translate the network address into the corresponding physical address and decide how to route data from the sender to the receiver
4. Transport Layer
Ensures reliable, ordered, and error-free data transmission to the target
5. Session Layer
Establishes and maintains communications between two nodes in the network.
6. Presentation Layer
Translation Officer between applications and networks
7. Application Layer
Provides interfaces to the software to enable the program to use network services.
Socket)
Sockets are used to connect client programs and server programs on the network. That is to say, there is always a connection between two communication programs on the network. The endpoint of this connection is called a socket. Sockets communicate at a lower level.
The socket is responsible for communication between processes on the network. The client program can write a request to the socket, and the server will process the request and send the processing result back through the socket. Specifically, server applications usually listen on a specific port to wait for a connection request from the customer. When a connection request arrives, the customer and the server establish a communication connection, during the connection, the customer is assigned a local port number and connected to a Socket. The customer writes a Socket to notify the server, and then reads the Socket to obtain the information sent by the server. Similarly, the server obtains a local port number, which needs a new port number to listen for other connection requests on the original port. The server also connects a Socket to its local port and communicates with the customer through reading and writing.
Sockets can be classified based on the communication nature, which is visible to users. Generally, applications only communicate with sockets of the same type. However, as long as the underlying communication protocol permits, different types of sockets can also communicate.
Currently, you can use two sockets: stream socket and datagram socket. Stream sockets provide bidirectional, ordered, non-repetitive, and non-record-Free Data Stream Services. TCP is a stream SOCKET protocol. The datagram socket supports two-way data streams, but it is not guaranteed to be reliable, orderly, and non-repetitive. That is to say, A process receiving information through a datagram socket may find that the information is duplicated, or it is different from the sending order. An important feature of a datagram socket is that it retains the record boundary. UDP is a datagram socket protocol.
Procedure for creating a TCP-based program:
1. The server creates a ServerSocket and calls the accept () method to wait for the client to connect. 2. The client creates a Socket and requests a connection with the server. 3. the server accepts the request connection and starts to create a new Socket to establish a leased line connection with the customer. 4. two sockets with connections are created in a separate thread (created by a server program. the server starts waiting for new connection requests.
Java-implemented Datagram
In java, two classes of DatagramSocket and DatagramPacket are provided to support data packet communication using mongoramsocket: a socket for sending and receiving data packets; multiple packages may go through different paths, and can reach the destination in any order. DatagramPacket: indicates a data packet. It is used to implement a transfer service without a connection package. A message sent from one machine to another depends only on the messages contained in this package. Example:
Network Protocol: TCP/IP protocol
TCP protocol: Transmission Control Protocol, used to provide reliable packet stream transmission for data and connection services for upper-layer applications. TCP uses ordered responses, it can re-transmit packets as needed to establish link-oriented communication between two or more hosts.
IP protocol: used to manage the message transmission between the client and the server. It is the cornerstone of all internet protocols. It is a packet-oriented protocol and is connectionless.
UDP protocol
UDP protocol: Also known as the User Datagram Protocol. It is another host-to-host layer protocol of the IP protocol. Provides a basic, low-latency data transmission
Port
Port is a logical concept. Each server runs on an open port on the host. A host can have multiple servers, that is, multiple ports. Programmers can use other ports (except the default ports) when creating their own server programs ). A port is usually numbered by a number. You can specify a port number to connect to the server to receive services.
Socket Communication
One-to-one Socket C/S communication TCP is a reliable connection-based network protocol, which is mostly interconnected over the Internet. The two processes on the network use the C/S Mode for communication. When two hosts are preparing to talk to each other, they must establish a Socket, one of which serves as the server to open a Socket and listen for connection requests from the network, and the other as the customer, it sends a request to the server on the network and transmits information to the server through Socket. To establish a connection, you only need to specify the IP address and port of the host.
Void close () to close this socket.
InetAddress getInetAddress () returns the address of the socket connection.
Int getLocalPort () returns the local port bound to this socket.
SocketAddress getLocalSocketAddress () returns the address of the endpoint bound to this socket. If not, null is returned.
Int getSoTimeout () to restore the SO_TIMEOUT setting.
Boolean isClosed () returns the socket closed state.
Void setSoTimeout (int timeout) enables/disables SO_TIMEOUT with the specified timeout value, in milliseconds.
String toString () returns the socket implementation address and implementation port in String format.
InetAddress
The InetAddress class is mainly used to obtain the specified network address. The InetAddress class does not have an explicit constructor. To generate an InetAddress object, you must use an available factory method. Factory method is only a static method in a class that returns a convention for this class instance. This is done in an overloaded constructor with a list of parameters. The result can be clearer when the unique method name is held.
There are three methods for InetAddress to create an InetAddress instance.
static InetAddress getLocalHost( ) throws UnknownHostExceptionstatic InetAddress getByName(String hostName) throws UnknownHostExceptionstatic InetAddress[ ] getAllByName(String hostName) throws UnknownHostException
Non-static method of InetAddress class
Boolean equals (Object other) returns true if the Object has the same Internet address as other.
Byte [] getAddress () returns the original IP address of the InetAddress object.
String getHostAddress () returns the host address String associated with the InetAddress object.
String getHostName () returns the String of the host name associated with the InetAddress object.
Int hashCode () returns the hash code of the called object.
Boolean isMulticastAddress () returns true if the Internet address is a multicast address; otherwise, false.
String toString () returns the host name String and IP address.
URL
The URL class encapsulates the method of using the Uniform Resource Locator (Uniform Resource Locator) to access resources on a WWW. This class can generate an object addressing or pointing to a resource. Objects generated by the URL class point to WWW resources (web pages, text files, graphic files, audio segments, and so on)
The basic URL representation is as follows:
Protocol: // hostname: port/resourcename # anchor constructor public URL (String spec) constructs a URL object using a String that represents the URL address. See the following statement: URL urlBase = new URL ("http: // www. 263.net/ "); public URL (URL context, String spec) constructs a URL object through the base URL and relative URL. See the following statement: URL net263 = new URL ("http://www.263.net/"); URL index263 = new URL (net263, "index.html") public URL (String protocol, String host, string file); URL url = new URL ("http", "www.gamelan.com", "/pages/Gamelan.net. html "); public URL (String protocol, String host, int port, String file); URL gamelan = new URL (" http "," www.gamelan.com ", 80, "Pages/Gamelan.network.html"); Common URL Methods: public String getProtocol (). The protocol name of RL. Public String getHost () to obtain the Host Name of the URL. Public int getPort () gets the port number of the URL. If no port is set,-1 is returned. Public String getFile () gets the name of the URL file. Public String getQuery () gets the query information of this URL. Public String getPath () to obtain the URL path. Public String getAuthority () to obtain the URL permission information. Public String getUserInfo () to obtain user information. Public String getRef () gets a reference to this URL. The URL-type application URL class is often used to download network resources. The URL can get an object through the constructor (the constructor is the URL address), and The InputStream object can be obtained through the openStream () method of the object, after InputStream is obtained, resources on the website can be downloaded. The following is an instance. You can use the URL class to download an image from a website and save it to your local device.
URL url = new URL ("http://www.2cto.com/uploadfile/2016/0405/20160405095842914.gif");
InputStream in = url. openStream ();
FileOutputStream fout = new FileOutputStream (new File(“sohu.gif "));
Int a = 0;
While (a>-1)
{
// Read data
A = in. read ();
// Write data
Fout. write ();
}
fout.close(); in.close();}
URL url = new URL (http://www.baidu.com);
BufferedReader in = new BufferedReader (new InputStreamReader (url. openStream ()));
String line;
While (line = in. readLine ())! = Null ){
System. out. println (line );
}
In. close ();
} Catch (Exception e ){
E. printStackTrace ();
}
After learning this, we can search for other resources on the Internet, such as images, sounds, and files, all resources, as long as we know its URL, can be downloaded to the local device using the above method, in fact, we can refer to the above idea as a web crawler-like software or a simple download tool, and then download the resources we want from the network. If you are interested, you can try it by referring to other materials.
URLConnection
The openConnection () method in the URL class can generate a URLConnection object. The instance of the URLConnection class can be used to read and write resources referenced by this URL. In network programming, JAVA URLConnection is a common class that provides a very convenient interface, as long as the URL address of the host to be connected is provided, use the openConnection () method of the URL class to obtain an HttpURLConnection object. The HttpURLConnection class is a subclass of the URLConnection class, and then analyze the HTTP content to complete related tasks. In this way, the user does not have to consider the implementation details of the underlying layer, avoiding the cumbersome programming of Socket class code, so it is more common.
Common URLConnection Methods
String getHeaderField (String name) returns the value of the specified header field.
InputStream getInputStream () returns the input stream read from the connection opened here.
String getContentEncoding () returns the value of the content-encoding header field.
Int getContentLength () returns the value of the content-length header field.
String getContentType () returns the value of the content-type header field.
Long getDate () returns the value of the date header field.