Exploration of Java Network Programming | Lebyte


Hello, everyone, I am Lebyte Xiaole. Last time I told you about the output stream of IO stream in Java, Lebyte. This article will tell you about network programming.

The main contents are as follows:

  • network
  • Network Layering
  • IP Location
  • Port port
  • Network programming

I. Network

1. Concept

Networks connect computers in different areas to form local area networks, metropolitan area networks or wide area networks. The computer distributed in different geographical areas and special external equipment are interconnected by communication lines into a large-scale and powerful network system, so that many computers can easily transfer information to each other and share hardware, software, data information and other resources.

2. Main Functions

Resource sharing
– Information transmission and centralized processing
Balanced Load and Distribution Processing


3. Network Communication Protocol

In order to realize communication in computer networks, there must be some conventions, i.e. communication protocols, for speed, transmission code, code structure and transmission.

Standards are formulated for transmission control procedures, error control, etc.

4. Network Communication Interface

In order to enable dialogue between two nodes, it is necessary to establish communication tools (i.e. interfaces) between them so that information can be exchanged between them. The interface consists of two parts:

Hardware device: to achieve information transmission between nodes;
Software Devices: Agreements that specify communication between two parties

II. Network Layering

Because the connection between nodes is very complex, the complex components are decomposed into some simple components and then compounded. The most commonly used way of compounding is hierarchical mode, that is, the same layer can communicate with each other, the upper layer can call the next layer, and has nothing to do with the next layer.

1. Layering of Communication Protocol

2. Packaging

Encapsulation: From top to bottom, add protocol control information of related layer

3. Unwrapping

Unwrapping: Getting data, from bottom to top, removing control information of protocols at relevant layers

III. IP Location

(IP) is the abbreviation of Internet Protocol. The protocol of interconnection between networks is designed for the interconnection of computer networks to communicate with each other. In the Internet, it is a set of rules that enable all computer networks connected to the Internet to communicate with each other. It stipulates the rules that computers should abide by when communicating on the Internet. Any computer system manufactured by any manufacturer can be interconnected with the Internet as long as it complies with the IP protocol.

Port: Software 0-65535 that differentiates data flow should not use ports below 1024. Each protocol has its own port. Under the same protocol, the port can not repeat FTP:21 HTTP:80.


Port is a virtual concept, not that there are really several ports on the host. Through ports, multiple network applications can be run on a single host. Can be analogous: IP equivalent to the company, ports equivalent to the company’s departments, URLs, equivalent to the personnel of various departments.

V. Resource Transfer Protocol

TCP: TCP (transfer control protocol) calls are connection-oriented, secure, reliable and inefficient.
UDP: UDP (User Data Gram Protocol) sending short messages is not connection-oriented, insecure, data may be lost and efficient

VI. Network Programming

The IP address and DNS (Domain Name System) of the encapsulated computer have no port.
1) Method

2) Method
GetHostAddress () returns the IP address
GetHostName () Returns Domain Name | Local Computer Name

Contains ports for socket communication
1) Getting objects
InetSocketAddress(String hostname, int port)
InetSocketAddress(InetAddress addr, int port)

2) Method
GetAddress () returns the InetAddress object
GetPort () return port
GetHostName () returns domain name

3 、URL
1) 、URI(Uniform resource identifier)
Unified resource identifier, used to uniquely identify a resource.

2) 、URL( Uniform Resource Locator)
Unified Resource Locator, which is a specific URI. Unified resource locator consists of four parts: protocol and storage
The host domain name, file name and port number of the resource. URL is a guide to Internet “resources”. Resources can be simple files or directories, or references to more complex objects, such as queries to databases or search engines.

3) Principle of Network Crawler

public static void main(String[] args) throws IOException {
		URL url = new URL ("http://www.baidu.com"); home page default resource
// Obtaining resource network flow may lead to chaos: 1. insufficient bytes 2. inconsistent coding and decoding formats
		/*InputStream is=url.openStream();
		byte[]flush=new byte[1024];
		int len=0;
			System.out.println(new String(flush,0,len));
		BufferedReader br=new BufferedReader(new InputStreamReader(url.openStream(),"utf-8"));
		BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream("baidu2.html"),"utf-8"));
		String msg=null;
	// Download network content locally. Then data analysis and index building are also the first step of search engine.
			Bw. newLine (); // Add method to insert newline character
		Bw. flush (); // forced brush


4. UDP Programming: DatagramSocket DatagramPacket

User Data Gram Protocol, a connectionless transport layer protocol, provides simple and unreliable transactional information delivery services. Its characteristics are: non-connection-oriented; unreliable transmission; data may be lost.


1) Server:
Create server DatagramSocket class + specified port
(2) Prepare to receive container byte array + packaged into Datagram Packet data package
(3) Receiving data
(4) Analytical data
(5) Releasing resources

2) Client:
Create Client Datagram Socket Class + Specified Port
Preparing data byte array
(3) Packet encapsulation requires specifying the address and port of the packet to be sent, that is, the server and port.
(4) Sending data
(5) Releasing resources

5. TCP programming: Server Socket Socket

Transfer control protocol is a connection-oriented, reliable, byte-stream-based point-to-point communication protocol for Transport layer communication. TCP Three-way Handshake, similar to a call

1) Characteristics

Based on TCP protocol, point-to-point communication with stable connection is established; real-time, fast, high security, high occupancy of system resources, low efficiency; request-response mode:

A) Client: In network communication, the program that initiates communication for the first time is called Client program.

B), Server: The program waiting for connection in the first communication is called Server program.

Socket: Send TCP messages

ServerSocket: Create a server

Sockets are a data exchange mechanism between processes. These processes can be either on the same machine or over the network.

Connect to different machines. In other words, sockets act as communication endpoints. A single socket is an endpoint.

A pair of sockets constitutes a two-way communication channel, enabling non-associated processes to carry out data locally or through the network.

Exchange. Once a socket connection is established, the data can be sent bidirectionally or unilaterally in the same or different systems until it reaches its destination.

One of the endpoints closes the connection

2) Server:

Create server specified port

Waiting for Client Connection

(3) Analysis of received data


3) Client:

Connecting Server: Creating Client + Designating Server Address + Port

(2) Sending data

Lebyte original, reproduced please indicate the source.

So far as network programming is concerned, please keep an eye on Lebytes for more Java dry goods.

Recommended Today

Hadoop MapReduce Spark Configuration Item

Scope of application The configuration items covered in this article are mainly for Hadoop 2.x and Spark 2.x. MapReduce Official documents https://hadoop.apache.org/doc…Lower left corner: mapred-default.xml Examples of configuration items name value description mapreduce.job.reduce.slowstart.completedmaps 0.05 Resource requests for Reduce Task will not be made until the percentage of Map Task completed reaches that value. mapreduce.output.fileoutputformat.compress false […]