首頁  >  文章  >  後端開發  >  伺服器如何知道客戶端不再存在?

伺服器如何知道客戶端不再存在?

PHPz
PHPz轉載
2024-02-08 20:50:03413瀏覽

伺服器如何知道客戶端不再存在?

問題內容

我試圖了解TCP 的工作方式,到目前為止我所知道的是,如果「隨機」斷開連接,一側無法知道另一側是否仍然存在。這就是使用一些 PING/PONG 演算法或 TCP keep-alive 的原因。我創建了一個簡單的客戶端-伺服器應用程序,其中客戶端連接到伺服器,並在 10 秒後發送簡單的訊息。讓我困惑的是,在以下兩種情況下,伺服器如何知道客戶端不再存在:

  1. 我讓程式完全運行並完成 - 在這種情況下,伺服器關閉連接(我不明白伺服器如何知道客戶端不再存在,我沒有在客戶端的任何地方指出我正在關閉連接)
  2. 我在完成之前關閉了客戶端進程(在它向伺服器發送訊息之前) - 在這種情況下,伺服器列印以下訊息Error Reading: read tcp 127.0.0.1:8080->127.0. 0.1:60845 : wsarecv: 現有連線被遠端主機強行關閉. (同樣,我不明白它如何知道客戶端不再存在)

我假設作業系統(或 golang net 庫)參與其中,並且它在 TCP 連接真正關閉之前發送附加訊息或類似的訊息來處理這種情況。

歡迎任何幫助。下面是我使用的完整程式碼,因此您可以在本地或線上 Go Playground 中運行它。

client.go

package main

import (
    "fmt"
    "net"
    "time"
)

func main() {
    // Connect to the server
    conn, err := net.Dial("tcp", "localhost:8080")
    if err != nil {
        fmt.Println("Error connecting:", err)
        return
    }
    defer conn.Close()

    // Send a message to the server
    message := "Hello from client!"
    time.Sleep(10000 * time.Millisecond)
    conn.Write([]byte(message))

    // Read the response from the server
    buffer := make([]byte, 1024)
    n, err := conn.Read(buffer)
    if err != nil {
        fmt.Println("Error reading:", err)
        return
    }

    // Print the server's response
    fmt.Printf("Received response from server: %s\n", buffer[:n])
}

伺服器.go

package main

import (
    "fmt"
    "net"
)

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

    // Obtain and print the client's IP address when the connection is established
    clientAddr := conn.RemoteAddr()
    fmt.Printf("Client connected from IP address: %s\n", clientAddr)

    for {
        // Read data from the client
        buffer := make([]byte, 1024)
        n, err := conn.Read(buffer)
        if err != nil {
            fmt.Println("Error reading:", err)
            return
        }

        // Print received message
        fmt.Printf("Received message from client (%s): %s\n", clientAddr, buffer[:n])

        // Send a response back to the client
        response := "Hello from server!"
        conn.Write([]byte(response))
    }
}

func main() {
    // Start listening on a port
    listener, err := net.Listen("tcp", "127.0.0.1:8080")
    if err != nil {
        fmt.Println("Error listening:", err)
        return
    }
    defer listener.Close()

    fmt.Println("Server listening on port 8080")

    for {
        // Wait for a connection
        conn, err := listener.Accept()
        if err != nil {
            fmt.Println("Error accepting connection:", err)
            continue
        }

        // Handle the connection in a goroutine
        go handleConnection(conn)
    }
}

正確答案


我意識到我正在談論一些我不太熟悉的事情,所以我自己測試了它。玩具範例,在同一台機器上的三個獨立終端中:

監督:sudo tcpdump -tttt -i lo port 8887(您可能需要找出您的本機主機設備是什麼,也許是lo0,使用sudo tcpdump -D。觀察Flags 欄位:. 是ACK,其他應該不言而喻。)

伺服器:nc -l 8887

客戶端:nc localhost 8887

  • #客戶端:SYN
  • 伺服器:SYN ACK
  • 客戶端:ACK

在客戶端輸入內容並按 Enter

  • 客戶端:PSH ACK
  • 伺服器:ACK

在伺服器中輸入內容並按 Enter

  • 伺服器:PSH ACK
  • 客戶端:ACK

a) 停止客戶端,無論是透過 ctrl-c 或 sigkill:

  • 客戶端:FIN ACK
  • 伺服器:FIN ACK
  • 客戶端:ACK

b) 停止伺服器:

  • 伺服器:FIN ACK
  • 客戶端:ACK

然後停止客戶端:

  • 客戶端:FIN ACK
  • 伺服器:RST

本實驗是在 WSL/Ubuntu 上完成的。我還沒有編譯你的程序,但你可以自己測試你的場景。讓我驚訝的一件事是,即使我 sigkilled 客戶端進程,FIN 仍然被發送,這表明如果客戶端進程以開放端口終止,則由核心負責發送 FIN。另外,當伺服器端進程停止時,FIN 沒有傳送,這使得客戶端遇到 RST 回應。

TCP 協定的核心實作負責處理這個問題;除了 conn.Close() 中發生的情況外,這與 Go 完全無關。

以上是伺服器如何知道客戶端不再存在?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除