目录
1、服务端代码:
package main
import (
"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 main
import (
"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 {}
}