Skip to content

Instantly share code, notes, and snippets.

@zmackie
Forked from elico/client.go
Created November 18, 2017 14:29
Show Gist options
  • Save zmackie/3076dd60ebc40b0a6587a412d2a45dfd to your computer and use it in GitHub Desktop.
Save zmackie/3076dd60ebc40b0a6587a412d2a45dfd 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