Skip to content

Instantly share code, notes, and snippets.

@chenwaichung
Forked from elico/client.go
Created June 14, 2019 01:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chenwaichung/3025ece283ab272fa0b45b93cbdd16d9 to your computer and use it in GitHub Desktop.
Save chenwaichung/3025ece283ab272fa0b45b93cbdd16d9 to your computer and use it in GitHub Desktop.
golang tcp client connection alive check
package main
import (
"fmt"
"io"
"net"
"time"
)
func main() {
conn, _ := net.Dial("tcp", "127.0.0.1:8081")
err := conn.(*net.TCPConn).SetKeepAlive(true)
if err != nil {
fmt.Println(err)
return
}
err = conn.(*net.TCPConn).SetKeepAlivePeriod(30 * time.Second)
if err != nil {
fmt.Println(err)
return
}
notify := make(chan error)
go func() {
buf := make([]byte, 1024)
for {
n, err := conn.Read(buf)
if err != nil {
notify <- err
if io.EOF == err {
return
}
}
if n > 0 {
fmt.Println("unexpected data: %s", buf[:n])
}
}
}()
for {
select {
case err := <-notify:
fmt.Println("connection dropped message", err)
break
case <-time.After(time.Second * 1):
fmt.Println("timeout 1, still alive")
}
}
}
package main
import (
"fmt"
"io"
"net"
"time"
)
func handleConnection(conn net.Conn) {
defer conn.Close()
notify := make(chan error)
go func() {
buf := make([]byte, 1024)
for {
n, err := conn.Read(buf)
if err != nil {
notify <- err
return
}
if n > 0 {
fmt.Println("unexpected data: %s", buf[:n])
}
}
}()
for {
select {
case err := <-notify:
if io.EOF == err {
fmt.Println("connection dropped message", err)
return
}
case <-time.After(time.Second * 1):
fmt.Println("timeout 1, still alive")
}
}
}
func main() {
fmt.Println("Launching server...")
ln, _ := net.Listen("tcp", ":8081")
for {
conn, _ := ln.Accept()
go handleConnection(conn)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment