client代码
package main
import (
"fmt"
"net"
"time"
)
func main() {
for {
conn, err := net.Dial("tcp", "localhost:8090")
if err != nil {
fmt.Printf("socket error[Dial] %s", err.Error())
} else {
var d string
d = "Hello paofu!!"
conn.Write([]byte(d))
fmt.Println("Connected to localhost:8090")
defer func() { _ = conn.Close() }()
go func() {
for {
time.Sleep(time.Second * 30)
if !sendSocket(conn, "ping") {
break
}
}
}()
response := make([]byte, 1024)
for {
n, err := conn.Read(response)
if err != nil {
fmt.Printf("socket error[Read] %s", err.Error())
break
}
msg := string(response[:n])
fmt.Printf("socket receive %s", msg)
if err = conn.SetReadDeadline(time.Now().Add(time.Minute * 1)); err != nil {
fmt.Printf("socket error[SetReadDeadline] %s", err.Error())
return
}
}
}
time.Sleep(time.Second * 3)
}
}
func sendSocket(conn net.Conn, data string) bool {
if err := conn.SetWriteDeadline(time.Now().Add(time.Second * 30)); err != nil {
fmt.Printf("socket error[SetWriteDeadline] %s", err.Error())
return false
}
if _, err := conn.Write([]byte(data)); err != nil {
fmt.Printf("socket error[Write] %s", err.Error())
return false
}
fmt.Printf("socket send %s", data)
return true
}
|