概述
server端
package main
import (
"net"
"fmt"
"os"
"time"
)
func main() {
server := ":7373"
netListen, err := net.Listen("tcp", server)
if err != nil{
LogC("connect error: ", err)
os.Exit(1)
}
LogC("Waiting for Client ...")
for{
conn, err := netListen.Accept()
if err != nil{
LogC(conn.RemoteAddr().String(), "Fatal error: ", err)
continue
}
//设置短连接(10秒)
conn.SetReadDeadline(time.Now().Add(time.Duration(7)*time.Second))
go handleConnection(conn)
}
}
func handleConnection(conn net.Conn) {
defer conn.Close()
buffer := make([]byte, 1024)
for {
n, err := conn.Read(buffer)
if err != nil {
fmt.Println("server read err:",err)
return
}
Data := buffer[:n]
message := make(chan byte)
//心跳计时
go HeartBeating(conn, message, 9)
//检测每次是否有数据传入
go GravelChannel(Data, message)
}
}
func GravelChannel(bytes []byte, message chan byte) {
for _, v := range bytes{
message <- v
}
close(message)
}
func HeartBeating(conn net.Conn, message chan byte, timeout int) {
select {
case fk := <- message:
fmt.Println("心跳包:",string(fk))
conn.SetDeadline(time.Now().Add(time.Duration(timeout) * time.Second))
break
case <- time.After(5 * time.Second):
LogC("conn dead now")
conn.Close()
}
}
func LogC(v ...interface{}) {
fmt.Println(v...)
return
}
client端
package main
import (
"net"
"fmt"
"os"
"time"
)
func main() {
server := "127.0.0.1:7373"
tcpAddr, err := net.ResolveTCPAddr("tcp4",server)
if err != nil{
Log(os.Stderr,"Fatal error:",err.Error())
os.Exit(1)
}
conn, err := net.DialTCP("tcp",nil,tcpAddr)
if err != nil{
Log("Fatal error:",err.Error())
os.Exit(1)
}
Log(conn.RemoteAddr().String(), "connection succcess!")
go func() {
i := 0
for {
fmt.Println(i)
time.Sleep(time.Second)
i++
}
}()
time.Sleep(time.Second * 100)
//sender(conn)
Log("send over")
}
func sender(conn *net.TCPConn) {
defer func() {
fmt.Println("client close")
conn.Close()
}()
for i := 0; i < 4; i++{
_, err := conn.Write([]byte("p"))
if err != nil {
fmt.Println("client write err")
return
}
fmt.Println("conn write success")
time.Sleep(2 * time.Second)
}
for i := 0; i < 2 ; i++ {
_, err := conn.Write([]byte("p"))
if err != nil {
fmt.Println("client write err")
return
}
fmt.Println("conn write success")
time.Sleep(8 * time.Second)
}
for i := 0; i < 3; i++{
_, err := conn.Write([]byte("p"))
if err != nil {
fmt.Println("client write err")
return
}
fmt.Println("conn write success")
time.Sleep(2 * time.Second)
}
}
func Log(v ...interface{}) {
fmt.Println(v...)
return
}
最后
以上就是自信火龙果为你收集整理的Golang心跳包的全部内容,希望文章能够帮你解决Golang心跳包所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复