go语言实现心跳机制样例

目录

1、服务端代码:

2、客户端代码:

3、最终实现效果:


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 {}
}

3、最终实现效果:

相关推荐
努力努力再努力wz3 分钟前
【Linux进阶系列】:信号(下)
java·linux·运维·服务器·开发语言·数据结构·c++
21号 112 分钟前
21.事务和锁(重点)
开发语言·数据库
Dobby_0517 分钟前
【Go】C++ 转 Go 第(五)天:Goroutine 与 Channel | Go 并发编程基础
vscode·golang
zzzsde20 分钟前
【C++】stack和queue:使用&&OJ题&&模拟实现
开发语言·c++
Mintopia35 分钟前
🚀 Next.js Edge Runtime 实践学习指南 —— 从零到边缘的奇幻旅行
前端·后端·全栈
紫荆鱼41 分钟前
设计模式-备忘录模式(Memento)
c++·后端·设计模式·备忘录模式
软件2051 小时前
【JDK、JRE、JVM】
java·开发语言·jvm
Wind哥1 小时前
VS Code搭建C/C++开发调试环境-Windows
c语言·开发语言·c++·visual studio code
程序员爱钓鱼1 小时前
Python编程实战 · 基础入门篇 | 字典(dict)
后端·python·ipython
程序员爱钓鱼1 小时前
Python编程实战 · 基础入门篇 | 集合(set)
后端·python·ipython