-
-
Save cbluth/6b225b6f0f0507300b72421ce7905a12 to your computer and use it in GitHub Desktop.
golang tcp client connection alive check
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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") | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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