Created
February 27, 2015 05:44
-
-
Save jpillora/896239c915a6e814f541 to your computer and use it in GitHub Desktop.
Go Yamux Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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