Skip to content

Instantly share code, notes, and snippets.

@evbruno
Created March 28, 2025 17:15
Show Gist options
  • Select an option

  • Save evbruno/bde7390de02bb19a313aaf7a2059f2d3 to your computer and use it in GitHub Desktop.

Select an option

Save evbruno/bde7390de02bb19a313aaf7a2059f2d3 to your computer and use it in GitHub Desktop.
Testing net.DialTCP and net.TCPConn
// testing against socat:
// socat -u TCP-LISTEN:5555,reuseaddr,fork STDOUT
package main
import (
"fmt"
"net"
"time"
)
func main() {
addr, err := net.ResolveTCPAddr("tcp4", "127.0.0.1:5555")
if err != nil {
panic(err)
}
dialer := func() (*net.TCPConn, error) {
conn, err := net.DialTCP("tcp", nil, addr)
if conn != nil {
err = conn.SetKeepAlive(true)
if err != nil {
fmt.Printf("Unable to set keepalive - %s", err)
}
} else if err != nil {
fmt.Printf("Unable to dial - %s", err)
}
return conn, err
}
conn, _ := dialer()
pending := []string{}
for i := range 30 {
m := fmt.Sprintf("index=%02d phase=HelloTCP\n", i)
if conn == nil {
fmt.Println("No connection, re-dialing after 3 secs")
time.Sleep(3 * time.Second)
conn, err = dialer()
if err != nil {
fmt.Printf("Unable to re-dial- %s", err)
pending = append(pending, m)
continue
}
}
conn.SetWriteDeadline(time.Now().Add(100 * time.Millisecond))
n, err := conn.Write([]byte(m))
if err != nil {
fmt.Printf("Error writing message: %s idx: %d len: %d\n", err, i, n)
conn.Close()
conn = nil
pending = append(pending, m)
} else {
fmt.Println("Sent message idx", i, "bytes", n)
}
time.Sleep(3 * time.Second)
}
time.Sleep(1 * time.Second)
fmt.Println("App finished. Pending messages", pending)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment