2
0
mirror of https://github.com/soheilhy/cmux.git synced 2024-09-19 18:45:48 +08:00

Add websocket example

This commit fixes #1 and adds an example matcher for websocket.
This commit is contained in:
Soheil Hassas Yeganeh 2015-08-05 17:32:32 -04:00
parent a6c45318a5
commit d47edebeb9

View File

@ -2,6 +2,7 @@ package cmux_test
import ( import (
"fmt" "fmt"
"io"
"log" "log"
"net" "net"
"net/http" "net/http"
@ -10,6 +11,7 @@ import (
"google.golang.org/grpc" "google.golang.org/grpc"
"golang.org/x/net/context" "golang.org/x/net/context"
"golang.org/x/net/websocket"
grpchello "github.com/grpc/grpc-common/go/helloworld" grpchello "github.com/grpc/grpc-common/go/helloworld"
"github.com/soheilhy/cmux" "github.com/soheilhy/cmux"
@ -28,6 +30,17 @@ func serveHTTP(l net.Listener) {
s.Serve(l) s.Serve(l)
} }
func EchoServer(ws *websocket.Conn) {
io.Copy(ws, ws)
}
func serveWS(l net.Listener) {
s := &http.Server{
Handler: websocket.Handler(EchoServer),
}
s.Serve(l)
}
type ExampleRPCRcvr struct{} type ExampleRPCRcvr struct{}
func (r *ExampleRPCRcvr) Cube(i int, j *int) error { func (r *ExampleRPCRcvr) Cube(i int, j *int) error {
@ -66,6 +79,9 @@ func Example() {
// We first match the connection against HTTP2 fields. If matched, the // We first match the connection against HTTP2 fields. If matched, the
// connection will be sent through the "grpcl" listener. // connection will be sent through the "grpcl" listener.
grpcl := m.Match(cmux.HTTP2HeaderField("content-type", "application/grpc")) grpcl := m.Match(cmux.HTTP2HeaderField("content-type", "application/grpc"))
//Otherwise, we match it againts a websocket upgrade request.
wsl := m.Match(cmux.HTTP1HeaderField("Upgrade", "websocket"))
// Otherwise, we match it againts HTTP1 methods. If matched, // Otherwise, we match it againts HTTP1 methods. If matched,
// it is sent through the "httpl" listener. // it is sent through the "httpl" listener.
httpl := m.Match(cmux.HTTP1Fast()) httpl := m.Match(cmux.HTTP1Fast())
@ -74,6 +90,7 @@ func Example() {
// Then we used the muxed listeners. // Then we used the muxed listeners.
go serveGRPC(grpcl) go serveGRPC(grpcl)
go serveWS(wsl)
go serveHTTP(httpl) go serveHTTP(httpl)
go serveRPC(rpcl) go serveRPC(rpcl)