golang tcp never disconnects

王林
Release: 2023-05-15 10:21:37
Original
1113 people have browsed it

In Golang, TCP will disconnect by default after establishing a connection. This is because the TCP protocol itself needs to ensure the reliability of the connection. Once the connection is disconnected, a new connection will be re-established. But there are also some situations where we hope that the TCP connection will not be disconnected. For example, in high concurrency situations, frequent establishment of connections will put additional pressure on the server. So how to ensure that Golang TCP is not disconnected?

1. TCP Keep-Alive

TCP Keep-Alive is a mechanism provided by the TCP protocol to detect whether the connection is still active. When a TCP connection does not transmit data for a period of time, the Keep-Alive mechanism will send some specific detection packets to the peer to know whether the connection still exists. If the peer does not respond to the probe packet, it will be considered that the peer has disconnected and the connection will be actively closed. If the peer can respond to the probe packet, the connection still exists. We can use the TCP Keep-Alive mechanism to achieve Golang TCP non-disconnection.

1.1 Enable TCP Keep-Alive

To enable TCP Keep-Alive, we need to set the socket properties. Golang can use the TCPConn structure in the net package to represent a TCP connection. TCPConn provides many methods for operating TCP connections. Among them, the SetKeepAlive method can be used to set TCP Keep-Alive.

The sample code is as follows:

conn, err := net.Dial("tcp", "127.0.0.1:8080")
if err != nil {
    fmt.Println("dial error:", err)
    return
}
tcpConn := conn.(*net.TCPConn)
// 设置为开启 TCP KeepAlive,默认为不开启
tcpConn.SetKeepAlive(true)
Copy after login

1.2 Set TCP Keep-Alive parameters

TCP Keep-Alive has three parameters, and we can set these parameters through the setting method of TCPConn. They are KeepAlive, KeepAlivePeriod, and KeepAliveCount.

  • KeepAlive: Indicates whether to enable TCP Keep-Alive. The default is not enabled.
  • KeepAlivePeriod: Indicates the time interval for sending detection packets. The default is not set and is determined by the operating system.
  • KeepAliveCount: Indicates the number of times the detection packet is sent. The default is not set and is determined by the operating system.

We can set these three parameters according to actual needs.

The sample code is as follows:

tcpConn.SetKeepAlive(true)          // 开启 TCP Keep-Alive
tcpConn.SetKeepAlivePeriod(time.Duration(30) * time.Second) // 设置探测包发送时间间隔为 30 秒
tcpConn.SetKeepAliveCount(3)        // 设置探测包的发送次数为 3
Copy after login

1.3 Keep-Alive detection packet sending frequency

By default, the frequency of Keep-Alive detection packet sending is determined by the operating system. In most operating systems, TCP Keep-Alive probe packets are sent every 2 hours. If the frequency needs to be changed, this can be achieved by changing parameters in the operating system. In the Linux operating system, you can change the frequency of sending TCP Keep-Alive detection packets by modifying the parameters in the proc file system.

2. Use long connections

Another way to achieve non-disconnection of Golang TCP is to use long connections. A long connection refers to an uninterrupted connection between the client and the server. In the long connection mode, after the client establishes a connection with the server, the client can send a request at any time, and the server can also send a response at any time. This can reduce the overhead incurred when frequently establishing connections and improve server performance.

Regarding how to implement long connections, here is a simple sample code for reference.

package main

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

func main() {
    listen, err := net.Listen("tcp", ":8080")
    if err != nil {
        panic(err)
    }

    for {
        conn, err := listen.Accept()
        if err != nil {
            continue
        }
        go handle(conn)
    }
}

func handle(conn net.Conn) {
    defer conn.Close()

    reader := bufio.NewReader(conn)
    for {
        data, err := reader.ReadString('
')
        if err != nil {
            return
        }

        response := fmt.Sprintf("echo: %s", data)
        conn.Write([]byte(response))
    }
}
Copy after login

In the above sample code, we accept the client's request by starting a TCP service. When the client establishes a connection with the server, the server receives the client's request through a loop and returns a response. Since the connection between the server and the client will not be actively disconnected, the client can send requests to the server at any time.

3. Summary

This article introduces two methods to achieve non-disconnection of Golang TCP, namely using the TCP Keep-Alive mechanism and using long connections. In actual development, you should choose a method that suits you according to the actual situation. If you only use TCP connections lightly, it is recommended to use TCP Keep-Alive; if you need to send requests frequently, it is recommended to use long connections. No matter which method is used, in actual applications, attention needs to be paid to standardizing and protecting the security of the connection to avoid security loopholes.

The above is the detailed content of golang tcp never disconnects. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template