我试图理解结核病的运作方式,而我迄今知道的是,如果“兰多”脱节,一方能够知道另一方是否仍然在那里。 因此,使用一些PING/PONG算法或TCP固定值。 在客户与服务器连接、10秒后发出简单信息的情况下,我创建了一个简单的客户服务器应用程序。 令我困惑的是,服务器如何知道客户在以下两种情况下已不复存在:
- I let the program to completely run and finish - in this case the server closes the connection (I don t understand how can server know that the client is no longer there, I didn t indicate anywhere on the client side that I am closing the connection)
- I shut down the client process before it complete (before it send a message to the server) - in this case the server prints the following message
Error reading: read tcp 127.0.0.1:8080->127.0.0.1:60845: wsarecv: An existing connection was forcibly closed by the remote host.
(Again, I don t understand how it can know that the client is no longer there)
我的假设是,本组织(或golang net>
Library)在此参与,并在清洁发展机制连接真正关闭或象处理这种情况那样发出额外信息。
任何帮助都是受欢迎的。 下面是我使用的完整代码,因此,你可以在当地或在线游乐场管理。
客户。
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
", buffer[:n])
}
服务器。
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
", 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
", 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)
}
}