mirror of
https://github.com/soheilhy/cmux.git
synced 2024-11-09 19:21:52 +08:00
Add websocket example
This commit fixes #1 and adds an example matcher for websocket.
This commit is contained in:
parent
a6c45318a5
commit
d47edebeb9
@ -2,6 +2,7 @@ package cmux_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
@ -10,6 +11,7 @@ import (
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"golang.org/x/net/context"
|
||||
"golang.org/x/net/websocket"
|
||||
|
||||
grpchello "github.com/grpc/grpc-common/go/helloworld"
|
||||
"github.com/soheilhy/cmux"
|
||||
@ -28,6 +30,17 @@ func serveHTTP(l net.Listener) {
|
||||
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{}
|
||||
|
||||
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
|
||||
// connection will be sent through the "grpcl" listener.
|
||||
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,
|
||||
// it is sent through the "httpl" listener.
|
||||
httpl := m.Match(cmux.HTTP1Fast())
|
||||
@ -74,6 +90,7 @@ func Example() {
|
||||
|
||||
// Then we used the muxed listeners.
|
||||
go serveGRPC(grpcl)
|
||||
go serveWS(wsl)
|
||||
go serveHTTP(httpl)
|
||||
go serveRPC(rpcl)
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user