.NET network programming - TCP communication

1. Basic concepts of network programming:

1. Internet

        It is to connect computers in different regions together to form a local area network, a metropolitan area network or a wide area network. The computers in different geographical regions are interconnected with specialized external equipment to form a large-scale and powerful network system, so that many computers can easily transmit information to each other and share resources such as hardware, software, and data information.

2. Computer network 

        Through transmission media, communication facilities and network communication protocols, multiple computers with independent functions and their external devices in the same geographical location are connected to realize resource sharing and data transmission system.

3. Communication protocol

To realize communication in computer network, there must be some communication protocol regulations, and standards should be established for transmission code, code structure, error control of transmission control steps, etc.

4. Communication interface

In order to enable dialogue between two nodes, a communication tool (that is, an interface) must be established between them to enable information exchange between them.

5. Network layering

       1. Since the connection between nodes is very complicated, when specifying the protocol, decompose the complex components into some simple components, and then combine them. The most commonly used composite method is the hierarchical method, that is, the same layer can communicate, the upper layer can call the next layer, and has no relationship with the next layer

        2. TCP/IP is a protocol family, which is also divided into four layers: application layer, transport layer, interconnection network layer, interface layer (physical + data link layer)

        3. The OSI network communication protocol model is a reference model, while the TCP/IP protocol is the de facto standard. The TCP/IP protocol refers to the OSI model, but it is not strictly divided according to the seven-layer standard stipulated by OSI, but only divided into four layers, which will be simpler. When there are too many layers, it is difficult for you to distinguish which layer a certain protocol belongs to.

2. Three elements of network programming 

1. IP address

        In order for computers in the network to communicate with each other, an identification number must be assigned to the computer, through which the computer to receive data and the computer to identify the sender must be specified, and the IP address is the identification number, which is the identification of the device.

1.1 IP addresses are divided into two categories

  1. IPv4: A 32bit address is assigned to each host connected to the network. According to the TCP/IP regulations, IP addresses are expressed in binary, and the length of each IP address is 32 bits, that is, 4 bytes.
  2. IPv6: Due to the vigorous development of the Internet, the demand for IP addresses is increasing, but the network address resources are limited, making the allocation of IP more and more tense. In order to expand the address space, the address space is redefined through IPv6, and the address length is 128bit. Each group of 16 bytes is divided into 8 groups of hexadecimal numbers, which solves the problem of insufficient network address resources.

1.2 InetAddress class (use InetAddress class to represent IP in Java)

        Commonly used methods:

String getHostAddress () Returns the IP address string (in text representation)
String getHostName () Returns the hostname for this IP address
Byte[] getAddress () Returns the original IP address of this InetAddress object

2. Port

2.1  Concept:

        Network communication is essentially communication between two applications, and each computer has many applications. The IP address uniquely identifies the device on the network, and the port number uniquely identifies the application in the device, that is, the identifier of the application.

2.2  Port number:

        An integer represented by two bytes, its value range is 0~65535. Among them, port numbers between 0 and 1023 are used for some well-known network services and applications, and common applications need to use port numbers above 1024. If the port number is occupied by another service or application, it will cause the current program to fail to start.

2.3 IntetSocketAddress class

        Contains IP and port information, often used in Socket communication. This class implements socket numeric address (IP address + port number) and does not depend on any protocol.

        Commonly used methods:

InetAddress getAddress() getInetAddress
Int getPort () get port number
String getHostName() get hostname

3. Agreement

        Multiple computers can be connected through a computer network, and computers in the same network need to abide by certain rules when connecting and communicating, just like a car on the road must obey the traffic rules. In computer networks, these rules for connection and communication are called network communication protocols. It makes unified regulations on the data transmission format, transmission rate, and transmission steps, and both parties in the communication must abide by it at the same time to complete the data exchange.

3.1 UDP protocol

  1. User Datagram Protocol
  2. UDP is a pre- wireless communication protocol , that is, when data is transmitted, the sender and receiver of the data do not establish a logical connection . To put it simply, when a computer sends data to another computer, the sender will send the data without confirming the existence of the receiver. Similarly, when the receiver receives the data, it will not feedback to the sender whether it has received the data.
  3. Because the UDP protocol consumes less resources and has high communication efficiency, it is usually used for audio, video and ordinary data transmission
  4. For example, video conferencing usually uses the UDP protocol, because even if one or two data packets are occasionally lost in this situation, it will not have a great impact on the acceptance result. However, when using the UDP protocol to transmit data, due to the connectionless nature of UDP, the integrity of the data cannot be guaranteed, so it is not recommended to use the UDP protocol when transmitting important data.

3.2 TCP protocol

  • Transmission Control Protocol (Transmission Control Protocol)
  • The 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 the data is transmitted. It provides a reliable and error-free data connection between two computers. In the TCP connection, the client and the server must be clearly defined. Since the client sends a connection request to the server, each connection creation needs to go through a "three-way handshake";

3.3 Three-way handshake

In the TCP protocol, in the preparation stage of sending data, there are three interactions between the client and the server 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

The second handshake: The server sends a response back to the client, notifying the client that the connection request has been received

The third handshake: the client sends confirmation information to the server again to confirm the connection

        After completing the three-way handshake connection establishment, the client and server can start data transmission. Due to this connection-oriented feature, the TCP protocol can guarantee the security of transmitted data, so it is widely used. Such as uploading files, downloading files, browsing web pages.

3.3.1 Principle of TCP communication:

        The TCP communication protocol is a reliable network protocol. It establishes a Socket object at both ends of the communication, thereby forming a network virtual link at both ends of the communication. Once the virtual network link is established, the programs at both ends can communicate through the virtual link.

  • Use Socket network programming based on TCP protocol, use Socket object to represent the communication ports at both ends
  • The TCP protocol is based on the request-response mode, and the first program initiated by the client (Client) program
  • The program waiting for connection in the first communication is blocked by the server (Serser) program
  • Use IO stream to realize data transmission

Four, TCP implementation steps (chat case)

1. Steps

1. Specify a port number on the server to create a ServerSocket, and use the accept method to listen, which will block the server thread and wait for user requests.

2. Specify the host IP and port number of the service on the client side to create a socket, and connect to the ServerSocket on the server side. At this time, the accept method on the server side is awakened, and at the same time returns a socket that communicates with the client side.

3. Use sockets on the client side and the server side to obtain network communication input/output streams, and perform read/write operations on the socket according to a certain communication protocol.

4. After the communication is completed, close the socket in the client and the server respectively.

2. Server side

  1. Create a ServerSocket (int port) object        
  2. Use the accept method on the Socket to listen to the client's connection request (blocking and waiting for the connection function)
  3. Accept and process the request information • Return the processing result to the client
  4. Close the stream and Socket object

3. Client

  1. Create a Socket (Strng host, int port) object
  2. Send a connection request to the server • Send a service request to the server • Receive the service result (service response)
  3. Close the stream and Socket object

4. ServerSocket class

Commonly used constructors: ServerSocket(int port) Create a server socket bound to the specified port

Common methods: Socket accept() listens to connect to this socket and accepts it

Java provides the Socket class for the client and the ServerSocket class for the server

Construction method:

Socket (InetAddress address, int port) address (IP address), port (port number)

Create a stream socket and connect it to the specified port number at the specified IP address;

Common methods:

OutoutStream getOutputStream() Returns the socket's output stream
InputStream getInputStream () Returns the socket's input stream
Void shutdownOutput() Disable the socket's output stream 

5. Use the wireless chat function between the client and the server

1. server

package com.net;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * 服务器
 * @author 云村小威
 *
 * @2023年7月19日 下午10:02:11
 */
public class Server {

	public static void main(String[] args) throws Exception {
		System.out.println("⁎⁎⁎⁎⁎⁎服务端⁎⁎⁎⁎⁎⁎");

		/* 创建服务器连接对象 */
		ServerSocket ss = new ServerSocket(6666);
		System.out.println("服务器已开启,等待连接...");

		/* 调用accept方法,客服端没有启动连接不能执行下一步(阻塞功能) */
		Socket server = ss.accept();
		System.out.println("客户端连接成功");

		/* 获取输入流,读取客户端发送的数据 */
		InputStream inputStream = server.getInputStream();
		BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));

		/* 获取输出流,向客户端回写数据 */
		Scanner zw = new Scanner(System.in);

		OutputStream outputStream = server.getOutputStream();
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream));

		while (true) {
			String readLine = br.readLine();
			System.out.println("客户端 :" + readLine);

			if ("拜拜".equals(readLine)) {
				System.out.println("再见");
				break;
			}

			System.out.println("请输入发送到客户端的内容:");
			String test = zw.next();
			/* 向客户端写入内容 */
			bw.write(test);
			bw.newLine();
			bw.flush();

			if ("拜拜".equals(test)) {
				System.out.println("再见");
				break;
			}
		}

		/* 关闭资源 */
		bw.close();
		outputStream.close();
		br.close();
		inputStream.close();
		server.close();
		ss.close();
	}
}

2. Client

package com.net;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;

/**
 * 客户端
 * @author 云村小威
 *
 * @2023年7月19日 下午10:02:00
 */
public class Client {

	public static void main(String[] args) throws Exception {
		System.out.println("⁕⁕⁕⁕⁕客户端⁕⁕⁕⁕⁕");

		/* 创建Socket对象,请求连接 */
		Socket client = new Socket(InetAddress.getByName("127.0.0.1"), 6666);
		System.out.println("服务器连接成功...");

		/* 获取输出流对象,向服务器写入数据 */
		OutputStream outputStream = client.getOutputStream();
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream));

		/* 获取输入流对象,读取服务器数据 */
		InputStream inputStream = client.getInputStream();
		BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));

		/* 向服务器发送信息 */
		Scanner zw = new Scanner(System.in);
		while (true) {
			System.out.println("请输入发送到服务器的内容:");
			String test = zw.next();
			/* 向服务器写入内容 */
			bw.write(test);
			bw.newLine();
			bw.flush();
			if ("拜拜".equals(test)) {
				System.out.println("再见");
				break;
			}
			/* 每次读取一个字节数组 */
			String content = br.readLine();
			System.out.println("服务器 : " + content);
			if ("拜拜".equals(content)) {
				System.out.println("再见");
				break;
			}
		}

		/* 关闭资源 */
		br.close();
		inputStream.close();
		bw.close();
		outputStream.close();
		client.close();
	}
}

3. Console version effect

209fc2eac0a14234bd5ad4511ee33711.gif

    Thank you for watching, I will continue to update this column, and update multi-threading and other knowledge in the future. Next, you can use multi-threading to realize the real-time wireless chat function of the form, please click to enter JAVA multi-threading  !

Guess you like

Origin blog.csdn.net/Justw320/article/details/131817953