1、服务端代码:
package mainimport ("fmt""net"
)func handleClient(conn net.Conn) {defer conn.Close()fmt.Println("Client connected:", conn.RemoteAddr())// 读取客户端的数据buffer := make([]byte, 1024)for {n, err := conn.Read(buffer)if err != nil {fmt.Println("Error reading:", err)return}// 处理接收到的数据data := string(buffer[:n])fmt.Printf("Received from %s: %s\n", conn.RemoteAddr(), data)// 回复心跳响应response := "Heartbeat response"conn.Write([]byte(response))}
}func main() {listener, err := net.Listen("tcp", ":8080")if err != nil {fmt.Println("Error:", err)return}defer listener.Close()fmt.Println("Heartbeat server listening on :8080")for {conn, err := listener.Accept()if err != nil {fmt.Println("Error accepting connection:", err)continue}// 启动一个goroutine处理客户端连接go handleClient(conn)}
}
2、客户端代码:
package mainimport ("fmt""net""time"
)func sendHeartbeat(conn net.Conn) {for {// 发送心跳数据heartbeat := "Heartbeat message"conn.Write([]byte(heartbeat))// 等待一段时间再发送下一次心跳time.Sleep(time.Second * 5)}
}func main() {conn, err := net.Dial("tcp", "localhost:8080")if err != nil {fmt.Println("Error connecting to server:", err)return}defer conn.Close()fmt.Println("Connected to server:", conn.RemoteAddr())// 启动goroutine发送心跳go sendHeartbeat(conn)// 主goroutine保持运行,等待心跳select {}
}
3、最终实现效果: