[Go] Explain TCP programming in detail

Table of contents

1. TCP protocol

2. TCP server

3. TCP client

4. Results display


1. TCP protocol

TCP (Transmission Control Protocol, Transmission Control Protocol) is a connection-oriented, reliable, byte stream-based network transmission protocol. It is one of the core protocols in the Internet protocol suite (TCP/IP) and is used to transmit data reliably in computer networks.

The characteristics and working principle of TCP are as follows:

  1. Connection-oriented: Before data transmission, the sender and receiver must first establish a connection. The process of connection establishment includes a three-way handshake, that is, the sender sends a connection request, the receiver replies with confirmation, and finally the sender replies with confirmation again. After the connection is established, both parties can transmit data through the connection.

  2. Reliability: TCP provides reliable data transmission, ensuring that data arrives at its destination in the correct order. It uses mechanisms such as sequence numbers, acknowledgments, and retransmissions to achieve reliability. If the receiver detects missing or out-of-sequence data, it sends a corresponding acknowledgment to the sender and asks the sender to resend.

  3. Byte stream transmission: TCP treats data as a series of byte streams, rather than splitting it into fixed-length packets. The sender divides the data into data blocks of appropriate size and encapsulates them in TCP segments for transmission. The receiver is responsible for reassembling the segments so that the original data stream can be restored.

  4. Congestion Control: TCP implements congestion control mechanisms to avoid network congestion and ensure fair sharing of network resources. By dynamically adjusting the sending rate, TCP can reduce the amount of data sent when the network is congested to prevent packet loss and performance degradation.

  5. IP-based: TCP is built on top of the IP protocol. It uses the network transmission service provided by the IP protocol to realize the reliable transmission of data, and also provides its own reliability mechanism.

TCP plays an important role as a bridge between the application layer and the transport layer, which provides a reliable, connection-oriented data transmission method for applications. Many common application layer protocols (such as HTTP, FTP, SMTP, etc.) are based on TCP for data transmission.

2. TCP server

The following is a simple TCP server-side workflow:

  1. Create Socket: The server first creates a Socket object for listening to the client's connection request. When creating a Socket, you need to specify the IP address and port number.

  2. Binding address and port: The server side binds the Socket to a specific IP address and port so that the client can find the server and connect. Usually the server should choose a fixed port number that will not conflict with other services.

  3. Listening connection: The server calls the listening function and begins to wait for the connection request from the client. The listening function will enter the blocking state until a new connection request arrives. Generally use listenthe function to start monitoring.

  4. Accept connection: When a client connection request arrives, the server acceptaccepts the connection through a function and creates a new Socket object to communicate with the client. The server can exchange data with the client through this new Socket object.

  5. Data exchange: Once the connection is established, the server and the client can transmit and exchange data by reading and writing the Socket. The server can receive the data sent by the client, and process and reply according to the protocol.

  6. Close connection and release resources: When the communication ends, the server can call closea function to close the connection, release related resources, and notify the client that the connection has been closed. Usually, the server will accept connection requests from multiple clients through a loop.

It should be noted that the server may need to use multiple threads or processes to handle concurrent connections from multiple clients. This allows multiple clients to be serviced at the same time without blocking other clients' connection requests.

The TCP server code implemented by the net package of Go language is as follows:

package main

import (
	"bufio"
	"fmt"
	"net"
)

// 处理函数
func process(conn net.Conn) {
	defer conn.Close() // 关闭连接
	for {
		reader := bufio.NewReader(conn)
		var buf [128]byte
		n, err := reader.Read(buf[:]) // 读取数据
		if err != nil {
			fmt.Println("read from client failed, err:", err)
			break
		}
		recvStr := string(buf[:n])
		fmt.Println("收到client端发来的数据:", recvStr)
		conn.Write([]byte(recvStr)) // 发送数据
	}
}

func main() {
	listen, err := net.Listen("tcp", "127.0.0.1:20000")
	if err != nil {
		fmt.Println("listen failed, err:", err)
		return
	}
	for {
		conn, err := listen.Accept() // 建立连接
		if err != nil {
			fmt.Println("accept failed, err:", err)
			continue
		}
		go process(conn) // 启动一个goroutine处理连接
	}
}

3. TCP client

The TCP client code implemented using the net package of the Go language is as follows:

package main

import (
	"bufio"
	"fmt"
	"net"
	"os"
	"strings"
)

// 客户端
func main() {
	conn, err := net.Dial("tcp", "127.0.0.1:20000")
	if err != nil {
		fmt.Println("err :", err)
		return
	}
	defer conn.Close() // 关闭连接
	inputReader := bufio.NewReader(os.Stdin)
	for {
		input, _ := inputReader.ReadString('\n') // 读取用户输入
		inputInfo := strings.Trim(input, "\r\n")
		if strings.ToUpper(inputInfo) == "Q" { // 如果输入q就退出
			return
		}
		_, err = conn.Write([]byte(inputInfo)) // 发送数据
		if err != nil {
			return
		}
		buf := [512]byte{}
		n, err := conn.Read(buf[:])
		if err != nil {
			fmt.Println("recv failed, err:", err)
			return
		}
		fmt.Println(string(buf[:n]))
	}
}

4. Results display

Guess you like

Origin blog.csdn.net/fanjufei123456/article/details/132018212
Recommended