Skip to content

Instantly share code, notes, and snippets.

@yuchen
Forked from jpillora/client.go
Last active January 10, 2022 03:47
Show Gist options
  • Save yuchen/8f54ade25d57df9f50a0f22fe7109595 to your computer and use it in GitHub Desktop.
Save yuchen/8f54ade25d57df9f50a0f22fe7109595 to your computer and use it in GitHub Desktop.
[Go Yamux Example] yamux sample code #golang
package main
import (
"fmt"
"log"
"net"
"time"
"github.com/hashicorp/yamux"
)
func stream(session *yamux.Session, name string) {
stream, err := session.Open()
if err != nil {
log.Fatal(err)
}
for i := 0; i < 3; i++ {
n, err := stream.Write([]byte("hello " + name))
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s %d bytes written\n", name, n)
time.Sleep(time.Second)
}
}
func main() {
conn, err := net.Dial("tcp4", "localhost:3000")
if err != nil {
log.Fatalf("TCP dial: %s", err)
}
// Setup client side of yamux
session, err := yamux.Client(conn, nil)
if err != nil {
log.Fatal(err)
}
go stream(session, "foo")
go stream(session, "bar")
stream(session, "zip")
}
package main
import (
"io"
"log"
"net"
"github.com/hashicorp/yamux"
)
func stream(sconn net.Conn) {
buff := make([]byte, 0xff)
for {
n, err := sconn.Read(buff)
if err != nil {
if err == io.EOF {
break
}
log.Printf("Stream read error: %s", err)
break
}
log.Printf("stream sent %d bytes: %s", n, buff[:n])
}
}
func handle(conn net.Conn) {
log.Printf("TCP accepted")
// Setup server side of yamux
session, err := yamux.Server(conn, nil)
if err != nil {
log.Fatalf("Yamux server: %s", err)
}
for {
sconn, err := session.Accept()
if err != nil {
if session.IsClosed() {
log.Printf("TCP closed")
break
}
log.Printf("Yamux accept: %s", err)
continue
}
go stream(sconn)
}
}
func main() {
l, err := net.Listen("tcp4", "0.0.0.0:3000")
if err != nil {
log.Fatalf("TCP server: %s", err)
}
for {
conn, err := l.Accept()
if err != nil {
log.Fatalf("TCP accept: %s", err)
}
go handle(conn)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment