我试图了解 TCP 的工作方式,到目前为止我所知道的是,如果“随机”断开连接,一侧无法知道另一侧是否仍然存在。这就是使用一些 PING/PONG 算法或 TCP keep-alive 的原因。我创建了一个简单的客户端-服务器应用程序,其中客户端连接到服务器,并在 10 秒后发送一条简单的消息。让我困惑的是,在以下两种情况下,服务器如何知道客户端不再存在:
- 我让程序完全运行并完成 - 在这种情况下,服务器关闭连接(我不明白服务器如何知道客户端不再存在,我没有在客户端的任何地方指出我正在关闭连接)
- 我在完成之前关闭了客户端进程(在它向服务器发送消息之前) - 在这种情况下,服务器打印以下消息
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中文网其他相关文章!

有效的Go应用错误日志记录需要平衡细节和性能。1)使用标准log包简单但缺乏上下文。2)logrus提供结构化日志和自定义字段。3)zap结合性能和结构化日志,但需要更多设置。完整的错误日志系统应包括错误enrichment、日志级别、集中式日志、性能考虑和错误处理模式。

EmptyinterfacesinGoareinterfaceswithnomethods,representinganyvalue,andshouldbeusedwhenhandlingunknowndatatypes.1)Theyofferflexibilityforgenericdataprocessing,asseeninthefmtpackage.2)Usethemcautiouslyduetopotentiallossoftypesafetyandperformanceissues,

go'sconcurrencyModelisuniqueduetoItsuseofGoroutinesandChannels,offeringaleightweightandefficePparreactComparredTothread-likeModelsInlanguagesLikeLikejava,python,andrust.1)

go'sconcurrencyModeluessgoroutinesandChannelStomanageConconCurrentPrommmengement.1)GoroutinesArightweightThreadThreadSthAtalLeadSthAtalAlaLeasyParalleAftasks,增强Performance.2)ChannelsfacilitatesfacilitatesafeDataTaAexafeDataTaAexchangeBetnegnegoroutinesGoroutinesGoroutinesGoroutinesGoroutines,crucialforsforsynchrroniz

Interfaceand -polymormormormormormingingoenhancecodereusability and Maintainability.1)DewineInterfaceSattherightabStractractionLevel.2)useInterInterFacesForceFordEffeldIndentientIndoction.3)ProfileCodeTomanagePerformanceImpacts。

TheinitfunctioninGorunsautomaticallybeforethemainfunctiontoinitializepackagesandsetuptheenvironment.It'susefulforsettingupglobalvariables,resources,andperformingone-timesetuptasksacrossanypackage.Here'showitworks:1)Itcanbeusedinanypackage,notjusttheo

接口组合在Go编程中通过将功能分解为小型、专注的接口来构建复杂抽象。1)定义Reader、Writer和Closer接口。2)通过组合这些接口创建如File和NetworkStream的复杂类型。3)使用ProcessData函数展示如何处理这些组合接口。这种方法增强了代码的灵活性、可测试性和可重用性,但需注意避免过度碎片化和组合复杂性。

initfunctionsingoareAutomationalCalledBeLedBeForeTheMainFunctionandAreuseFulforSetupButcomeWithChallenges.1)executiondorder:totiernitFunctionSrunIndIndefinitionorder,cancancapationSifsUsiseSiftheyDepplothother.2)测试:sterfunctionsmunctionsmunctionsMayInterfionsMayInterferfereWithTests,b


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

Atom编辑器mac版下载
最流行的的开源编辑器

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

禅工作室 13.0.1
功能强大的PHP集成开发环境

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能