package main
import (
"fmt"
"net"
"time"
)
var ConnSlice map[net.Conn]*Heartbeat
type Heartbeat struct {
endTime int64
}
func main() {
ConnSlice = map[net.Conn]*Heartbeat{}
l, err := net.Listen("tcp", "127.0.0.1:8086")
if err != nil {
fmt.Println("連線失敗")
}
defer l.Close()
for {
conn, err := l.Accept()
if err != nil {
fmt.Println("Error accepting: ", err)
}
fmt.Printf("Received message %s -> %s \n", conn.RemoteAddr(), conn.LocalAddr())
ConnSlice[conn] = &Heartbeat{
endTime: time.Now().Add(time.Second * 5).Unix(),
}
go handelConn(conn)
}
}
func handelConn(c net.Conn) {
buffer := make([]byte, 1024)
for {
n, err := c.Read(buffer)
if ConnSlice[c].endTime > time.Now().Unix() {
ConnSlice[c].endTime = time.Now().Add(time.Second * 5).Unix()
} else {
fmt.Println("長時間未發訊息斷開連接")
return
}
if err != nil {
return
}
if string(buffer[0:n]) == "1" {
c.Write([]byte("1"))
continue
}
for conn, heart := range ConnSlice {
if conn == c {
continue
}
if heart.endTime < time.Now().Unix() {
delete(ConnSlice, conn)
conn.Close()
fmt.Println("刪除連接", conn.RemoteAddr())
fmt.Println("現在存有連結", ConnSlice)
continue
}
conn.Write(buffer[0:n])
}
}
}