Skip to content

Instantly share code, notes, and snippets.

@yifan-gu
Created February 7, 2014 17:57
Show Gist options
  • Save yifan-gu/8868121 to your computer and use it in GitHub Desktop.
Save yifan-gu/8868121 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"net"
"os"
"syscall"
"time"
)
func main() {
var err error
finish := make(chan bool, 1)
pipe := make([]*os.File, 2)
pipe[0], pipe[1], err = os.Pipe()
if err != nil {
panic(err.Error())
}
go func() {
fmt.Println("listen...")
ln, err := net.Listen("tcp", ":8080")
if err != nil {
panic(err.Error())
}
conn, err := ln.Accept()
if err != nil {
panic(err.Error())
}
fmt.Println("accepted!")
fmt.Println("splicing... buffer size:", 4096)
connFile, err := conn.(*net.TCPConn).File()
if err != nil {
panic(err.Error())
}
n, err := syscall.Splice(int(connFile.Fd()), nil, int(pipe[1].Fd()), nil, 4096, 0)
if err != nil {
panic(err.Error())
}
b := make([]byte, 4096)
_, err = pipe[0].Read(b)
if err != nil {
panic(err.Error())
}
fmt.Printf("recv: %scount: %d\n", string(b), n)
finish <- true
}()
select {
case <-finish:
fmt.Println("finish")
case <-time.After(10 * time.Second):
fmt.Println("time out")
}
}
package main
import (
"fmt"
"net"
"time"
)
func main() {
conn, err := net.Dial("tcp", ":8080")
if err != nil {
panic(err.Error())
}
for i := 0; i < 10; i++ {
b := fmt.Sprintf("hello %d", i)
conn.Write([]byte(b))
<-time.After(1 * time.Second)
}
conn.Close()
fmt.Println("done")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment