Java Native network programming

1、 Concept

Since its birth, Java language has been closely linked with the network. At the Sun World Conference in 1995, Netscape, which was the absolute leader in the browser market share at that time, announced that it supported Java in the browser, which led to the support of a series of company products for Java, making Java quickly become a popular language.

There are three main classes related to network functions provided by Java: URL, socket and daragram.

2、 URL and urlconnection

The URL class represents a uniform resource locator, which is a pointer to Internet resources. It is the class with the highest level or the most encapsulation among the three classes. You can directly send or read data on the network through the URL.

The URL class described above represents the location of a network resource, while urlconnection represents a connection. Instances of this class can be used to read or write resources referenced by the corresponding URL.

3、 Socket programming based on TCP

Socket is also called socket. Applications usually send requests to or respond to network requests through socket Socket programming in the Java language is commonly used in socket and ServerSocket.

ServerSocket is used for the server, and socket is used when establishing a network connection. When the connection is successful, a socket instance will be generated at both ends of the application. Operate this instance to complete the required session. For a network connection, sockets are equal and do not have different levels on the server or client. No matter socket or ServerSocket, their work is completed through socketimpl class and its subclasses.

TCP socket programming diagram:

Server program:

Client program:

4、 Socket programming based on UDP

UDP is a user datagram protocol. It provides connectionless and unreliable information transmission services. It is mostly used when audio and video can tolerate certain packet loss. Java mainly provides two classes to implement socket programming based on UDP:

Datagram socket: this class represents the socket used to send and receive datagram packets. Datagram socket is the sending or receiving point of packet delivery service. Each packet sent or received on datagram socket is addressed and routed separately. UDP broadcast sending is always enabled on datagram socket.

Datagram packet: this class represents a datagram packet. Datagram packet is used to realize connectionless packet delivery service. Each packet is routed from one machine to another only according to the information in the packet.

Example of UDP socket programming:

Server (receiver) program:

Client (sender) program:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>