Skip to content

Instantly share code, notes, and snippets.

@nfirvine
Created February 4, 2016 23:17
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 nfirvine/145394dee59405c5454e to your computer and use it in GitHub Desktop.
Save nfirvine/145394dee59405c5454e to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"net"
"sync"
"time"
)
func main() {
addr := net.TCPAddr{
IP: net.IPv4(127, 0, 0, 1),
Port: 12346,
}
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
l, _ := net.ListenTCP("tcp4", &addr)
conn, err := l.Accept()
if err != nil {
panic(err)
}
fmt.Println("accepted")
for {
conn.SetReadDeadline(time.Now().Add(time.Second * 5))
b := make([]byte, 1024)
fmt.Println("reading")
n, err := conn.Read(b)
fmt.Println("read")
if err != nil {
fmt.Println("err:", err)
time.Sleep(time.Millisecond * 100)
} else {
fmt.Printf("read %v; %#v (%T)\n", b[:n], err, err)
}
}
wg.Done()
}()
wg.Add(1)
go func() {
conn, _ := net.DialTCP("tcp4", nil, &addr)
time.Sleep(time.Second)
fmt.Println("client writing")
n, err := conn.Write([]byte{1, 2, 3, 4, 5})
fmt.Println("wrote", n, err)
fmt.Println("client sleeping")
time.Sleep(time.Second * 3)
n, err = conn.Write([]byte{6, 7, 8, 9, 0})
fmt.Println("wrote", n, err)
time.Sleep(time.Second * 3)
fmt.Println("client closing")
conn.Close()
wg.Done()
}()
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment