Java based network programming

Keywords: Java udp TCP/IP

Network programming

Network programming is a program that realizes the communication between two computers under a certain protocol.

1. What is a computer network

The computers distributed in different geographical areas and special external equipment are interconnected by communication lines to form 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.

Main functions of computer network
Resource sharing
Information transmission and centralized processing
Balanced load and distributed processing
Integrated information service (www / ISDN)

2. Basic concept of network

1. Protocol: the rules that must be observed in computer network communication.

2.IP address: refers to the Internet Protocol Address, commonly known as IP. IP addresses are used to uniquely number computer devices in a network.

IP address classification
IPv4: it is a 32-bit binary number, which is usually divided into 4 bytes and expressed in the form of a.b.c.d. for example, 192.168.65.100, where a, B, C and D are decimal integers between 0 and 255, so it can represent 4.2 billion at most.

IPv6: due to the vigorous development of the Internet, the demand for IP addresses is increasing, but the limited network address resources make the allocation of IP more and more tense. In order to expand the address space, it is proposed to redefine the address space through IPv6, adopt 128 bit address length, each 16 bytes is divided into 8 groups of hexadecimal numbers, expressed as ABCD:EF01:2345:6789:ABCD:EF01:2345:6789, It is said that it can compile a website for every grain of sand in the world, which solves the problem of insufficient network address resources.

Domain name: for example: www.sina.com.cn

Local IP: 127.0.0.1 is equivalent to localhost

3. Port number: an integer represented by two bytes. Its value range is 065535. Among them, the port numbers between 01023 are used for some well-known network services and applications, and ordinary applications need to use port numbers above 1024. If the port number is occupied by another service or application, the current program will fail to start.

Through the protocol + IP address + port number, the processes in the network can be identified, and the communication between processes can use this identification to interact with other processes

3. Network communication protocol

Multiple computers can be connected through the computer network. Computers located in the same network need to abide by certain rules when connecting and communicating. In the computer network, these connection and communication rules are called network communication protocol, which uniformly stipulates the data transmission format, transmission rate, transmission steps, etc, The data exchange can only be completed if both sides of the communication comply with it at the same time.

TCP/IP protocol: Transmission Control Protocol / Internet protocol, which is the most basic and extensive protocol on the Internet. It defines standards for how computers connect to the Internet and how data is transmitted between them. It contains a series of protocols for processing data communication, and adopts a 4-layer layered model. Each layer calls the protocols provided by its next layer to complete its own requirements.

The four layers of TCP/IP protocol are application layer, transmission layer, network layer and link layer. Each layer is responsible for different communication functions.
Link layer: the link layer is used to define the physical transmission channel. It is usually the driving protocol for some network connection devices, such as the driver provided for optical fiber and network cable.
Network layer: the network layer is the core of the whole TCP/IP protocol. It is mainly used to group the transmitted data and send the packet data to the target computer or network.
Transport layer: it mainly enables network programs to communicate. TCP protocol or UDP protocol can be used for network communication.
Application layer: mainly responsible for the application protocol, such as HTTP protocol, FTP protocol, etc.

4.TCP protocol

TCP: transmission control protocol. TCP protocol is a connection oriented communication protocol, that is, before transmitting data, a logical connection is established between the sending end and the receiving end, and then data is transmitted. It provides reliable and error free data transmission between two computers. In TCP connection, the client and the server must be clear, and the client sends a connection request to the server. Each connection creation needs to be approved "Three handshakes".

Three handshakes: in TCP protocol, three interactions between the client and the server in the preparation stage of sending data to ensure the reliability of the connection.
The first handshake, the client sends a connection request to the server and waits for the server to confirm.
In the second handshake, the server sends back a response to the client to notify the client that it has received the connection request.
For the third handshake, the client sends a confirmation message to the server again to confirm the connection

After three handshakes are completed and the connection is established, the client and server can start data transmission. Due to this connection oriented feature, TCP protocol can ensure the security of data transmission, so it is widely used, such as downloading files, browsing web pages, etc.

5.UDP protocol

UDP: User Datagram Protocol UDP is a connectionless communication protocol, that is, during data transmission, the sender and receiver of data do not establish a logical connection. In short, when one computer sends data to another computer, the sender will send data without confirming whether the receiver exists. Similarly, when the receiver receives data, it will not feed back whether it has received data to the sender.

Due to the low resource consumption and high communication efficiency of using UDP protocol, it is usually used for the transmission of audio, video and ordinary data. For example, video conference uses UDP protocol, because even if one or two packets are lost occasionally, it will not have a great impact on the reception results. However, when using UDP protocol to transmit data, due to the non connectivity of UDP, it can not be guaranteed Data integrity, so UDP protocol is not recommended when transmitting important data.

Features: the data is limited to 64kb, beyond which it cannot be sent.

6.TCP programming

6.1 server side

Server side:
1. Create ServerSocket object (and bind port)
2. Call the accept method and wait for the connection from the client
3. Call getXXXStream method for I/O
4. Close the Socket

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TestServerSocket {
	public static void main(String[] args) throws Exception {
		System.out.println("Server startup...");
		//Create a server and declare the port number
		ServerSocket server=new ServerSocket(9999);
		//Waiting for connection
		Socket socket=server.accept();
		//signal communication
		InputStream in=socket.getInputStream();
		OutputStream out=socket.getOutputStream();
		byte b[]=new byte[1024];
		in.read(b);
		//Receive information from the client
		System.out.println(new String(b).trim());
		//Send information to clients
		out.write("Hello, this is the server".getBytes());
		//close
		out.close();
		in.close();
		socket.close();
	}
}

6.2 client

client:
1. Create a Socket object and connect to the server
2. Call getXXXStream method for I/O
3. Close the Socket

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class TestClientSocket {
	public static void main(String[] args) throws Exception, IOException {
		System.out.println("Client startup...");
		//Create client and establish connection
		Socket  client=new Socket("127.0.0.1",9999);		
		//signal communication
		InputStream in=client.getInputStream();
		OutputStream out=client.getOutputStream();
		//Send message to server
		out.write("Hello server, I'm the client!".getBytes());
		
		byte b[]=new byte[1024];
		in.read(b);
		//Receive information from the server
		System.out.println(new String(b).trim());	
		//close
		out.close();
		in.close();
	}
}

7.UDP programming

7.1 server side

The server:
​ DatagramSocket socket = new DatagramSocket(9000)
​ DatagramPacket packet = DatagramPacket(byte[] buf, int,length)
​ socket.receive(packet)

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UDPserver {
	public static void main(String[] args) throws Exception {
		//Create server
		DatagramSocket server=new DatagramSocket(8888);
		//signal communication
		byte b [] =new byte[1024];
		DatagramPacket p=new DatagramPacket(b, 0, b.length);
		//receive data 
		server.receive(p);
		//print data
		System.out.println(new String(b).trim());
		//close
		server.close();
	}
}

7.2 client

client:
​ DatagramSocket socket = new DatagramSocket()
​ DatagramPacket packet = DatagramPacket(byte[] buf, int ,length, InetSoketAddress)
​ socket.send(packet)

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

public class UDPclient {
	public static void main(String[] args) throws Exception {
		//Create client
		DatagramSocket client=new DatagramSocket();
		//signal communication
		byte b [] ="Me or me, client".getBytes();
		//Package data
		DatagramPacket p=new DatagramPacket(b,0, b.length, 
				new InetSocketAddress("127.0.0.1", 8888));
		//Send packet
		client.send(p);	
		//close
		client.close();
	}
}

Posted by lupus2k5 on Mon, 04 Oct 2021 12:13:12 -0700