Skip to content

Instantly share code, notes, and snippets.

@elico
Created July 26, 2016 00:21
Show Gist options
  • Star 25 You must be signed in to star a gist
  • Fork 10 You must be signed in to fork a gist
  • Save elico/3eecebd87d4bc714c94066a1783d4c9c to your computer and use it in GitHub Desktop.
Save elico/3eecebd87d4bc714c94066a1783d4c9c 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)
}
}
@shenshouer
Copy link

shenshouer commented Dec 11, 2017

the code of client :

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 {
					close(notify)
					return
				}
			}
			if n > 0 {
				fmt.Println("unexpected data: %s", buf[:n])
			}
		}
	}()

	for {
		select {
		case err := <-notify:
			fmt.Println("connection dropped message", err)
			if err == io.EOF {
				fmt.Println("connection to server was closed")
				return
			}
			break
		case <-time.After(time.Second * 1):
			fmt.Println("timeout 1, still alive")
		}
	}

}

@erik9289
Copy link

Suggest change: fmt.Println("unexpected data: %s", buf[:n]) into fmt.Printf("unexpected data: %X", buf[:n])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment