Skip to content

Instantly share code, notes, and snippets.

@gohumble
Last active July 20, 2021 17:42
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 gohumble/d76e537d0fe8c714d32763fbf0c4da0d to your computer and use it in GitHub Desktop.
Save gohumble/d76e537d0fe8c714d32763fbf0c4da0d to your computer and use it in GitHub Desktop.
func (c *Connection) duplexPipe() {
upstreamChannel := chanFromConnection(c.upstream)
clientChannel := chanFromConnection(c.client)
for {
select {
case b1 := <-upstreamChannel:
if b1 == nil {
return
} else {
c.client.Write(b1)
}
case b2 := <-clientChannel:
if b2 == nil {
return
} else {
c.upstream.Write(b2)
}
}
}
}
func chanFromConnection(tcpConnection net.Conn) chan []byte {
channel := make(chan []byte)
go func() {
b := make([]byte, 2<<10)
for {
n, err := tcpConnection.Read(b) // --- blocking operation ---
if n > 0 {
res := make([]byte, n)
copy(res, b[:n])
channel <- res
}
if err != nil {
close(channel)
return
}
}
}()
return channel
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment