Skip to content

Instantly share code, notes, and snippets.

@radiospiel
Created September 7, 2014 10:03
Show Gist options
  • Save radiospiel/baa9f7f809ecab4eef63 to your computer and use it in GitHub Desktop.
Save radiospiel/baa9f7f809ecab4eef63 to your computer and use it in GitHub Desktop.
go bidirectional copying
func BidirectionalCopy(conn net.Conn, channel net.Conn) {
start := time.Now()
var done = make(chan int, 1)
go copy("to ssh channel", conn, channel, done)
go copy("from ssh channel", channel, conn, done)
written := <-done
conn.Close()
channel.Close()
written += <-done
seconds := time.Since(start).Seconds()
p := float64(written) / seconds / 1024 / 1024
nlog.WRN("transferred %d byte: %v: %.2f MByte/sec", written, time.Since(start), p)
}
func copy(label string, src io.Reader, dest io.Writer, done chan int) {
buf := make([]byte, 1024 * 16)
var written int
var err error
for {
var bytes int
bytes, err = src.Read(buf)
if err == nil {
bytes, err = dest.Write(buf[:bytes])
}
if err != nil {
break
}
nlog.DBG("%s: transferred %d bytes", label, bytes)
written += bytes
}
if err != io.EOF && strings.Index(err.Error(), "use of closed network connection") == -1 {
nlog.INF("copied %d byte %s before failing w/%v", written, label, err)
} else {
nlog.INF("copied %d byte %s", written, label)
}
done <- written
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment