[learn Java notes from scratch] network programming

Keywords: Java socket network Programming

You can pay attention to the author's account and the Java notebook from scratch. You can also go to the author's blog Garden to learn from the catalog. This film will be based on the black horse programmer job class video for learning and data sharing, and take notes and their own views. Welcome to study and discuss together.

[learn Java notes from scratch] directory

Socket is a mechanism provided for network programming; there are sockets at both ends of communication; network communication is actually the communication between sockets; data is transmitted through IO between two sockets.

Three elements of network communication

1.IP address

The IP address is the identification of the device in the network. You can enter ipconfig in the command prompt window for query. The IP address is represented by dotted decimal system. IPv4 is 32 bits, 4 bytes; IPv6 is 128 bits, 16 bytes.

2. port number

It is used to identify the logical address of the process and the identification of different processes

Port number
● physical port network interface
● logical port we mean logical port
Each network program will have at least one logical port
It is used to identify the logical address of the process and the identification of different processes
Valid port: 0 ^ 65535, where 0 ^ 1024 system uses or reserves port
● port number can be viewed through 360

3. Transmission protocol

Communication rules, common protocols: TCP, UDP
UDP agreement
Encapsulating data source and destination into data package, no connection is needed; the size of datagram is limited to 64k; no connection, unreliable protocol; no connection, fast
TCP agreement
It is a reliable protocol to establish a connection to form a channel for data transmission; to transmit large amount of data in the connection; to complete the connection through three handshakes; to establish a connection is necessary, and the efficiency will be slightly lower

InetAddress class

This class represents an Internet Protocol (IP) address

common method

static InetAddress getByName(String host): IP address can be obtained according to computer name or IP address
String getHostAddress(): returns the IP address string as text.
String getHostName(): gets the host name of this IP address.
static InetAddress getLocalHost(): returns the local host.

UDP protocol

UDP send data example

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPSendDemo {
	public static void main(String[] args) throws IOException {
		// Create sender Socket object
		/*
		 * DatagramSocket :This class is used to send and receive data. Datagram Socket(), based on UDP protocol, creates Socket object and randomly assigns port number
		 * DatagramSocket(int port) :Create Socket object and specify port number
		 */
		DatagramSocket ds = new DatagramSocket();

		// Create data and package
		/*
		 * DatagramPacket : This class represents the address of datagram data byte [] device address port number of ip process datagram packet (byte []
		 * buf, int length, InetAddress address, int port)
		 */
		String s = "Hello UDP!";
		byte[] bys = s.getBytes();
		int l = bys.length;
		InetAddress address = InetAddress.getByName("DESKTOP-PFN24DV");
		int port = 8888;
		// Pack
		DatagramPacket dp = new DatagramPacket(bys, l, address, port);
		// send data
		ds.send(dp);
		// Release resources
		ds.close();

	}

}

UDP accept data sample

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPReceiveDemo {
	public static void main(String[] args) throws IOException {
		//Create Socket object of receiver
		DatagramSocket ds = new DatagramSocket(8888) ;
		//Data received
		byte[] bys = new byte[1024];
		DatagramPacket dp = new DatagramPacket(bys, bys.length);
		ds.receive(dp);//Block, send first
		
		//Analytical data
		//InetAddress getAddress(): get IP object of sender
		InetAddress address = dp. getAddress();
		//byte[] getData(): get the received data, or directly use the array when creating the package object
		byte[] data = dp. getData();
		//int. getLength(): get the number of bytes of received data
		int length = dp. getLength() ;

		//output data
		System.out.println("sender:"+address);
		System.out.println("data:"+new String(data,0,data.length));
		System.out.println("length:"+length);
		//Release resources
		ds.close();
	}

}

Precautions for using UDP

1. The port number is wrong, the data can be sent normally without exception, but the data cannot be received
2. Exception in thread "main" Java. Net. Bindexception: address already in use: cannot bind: port number already bound

TCP send data example

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

public class TCPClientDemo {
	public static void main(String[] args) throws UnknownHostException, IOException {
		//Create sender Socket object (create connection) 
		//Socket (InetAddress address, int port )
		Socket s  = new Socket(InetAddress.getByName("DESKTOP-PFN24DV"),10086);
		//Get output stream object
		OutputStream os = s.getOutputStream();
		//send data
		String str = "Hello, TCP!";
		os.write(str.getBytes());
		//Release resources
		s.close();

	}

}

TCP receive data example

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

public class TCPServerDemo {
	public static void main(String[] args) throws IOException {
		// Create Socket object of receiver
//		ServerSocket: receiver, server Socket
//		ServerSocket(int port )
		ServerSocket ss = new ServerSocket(10086);

		// Monitor (block)
//		Socket accept()
		Socket s = ss.accept();
		// Get input stream object
		InputStream is = s.getInputStream();

		// get data
		byte[] bys = new byte[1024];
		int len = is.read(bys);
		// output data
		System.out.println(new String(bys,0,len));
		// Release resources
		s.close();

	}

}

Precautions for using TCP

Exception in thread "main" Java. Net. Connectexception: connection rejected: Connect: link failed, UDP will be ignored after sending, but TCP needs to establish a link, if only sending, no receiving, the link will fail

TCP's "three handshakes" and "four waves"

Detailed explanation of "three handshakes" and "four waves" of TCP connection

Posted by stevehossy on Tue, 07 Apr 2020 08:40:40 -0700