From 33541d18aeabc31c01433fb4858193ecaa8101b1 Mon Sep 17 00:00:00 2001 From: "M. J. Fromberger" Date: Wed, 6 Oct 2021 20:07:20 -0700 Subject: [PATCH] Add websocket server example. --- tools/examples/wshttp/server.go | 58 +++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 tools/examples/wshttp/server.go diff --git a/tools/examples/wshttp/server.go b/tools/examples/wshttp/server.go new file mode 100644 index 0000000..59ff3e8 --- /dev/null +++ b/tools/examples/wshttp/server.go @@ -0,0 +1,58 @@ +// Program wshttp demonstrates how to set up a JSON-RPC 20 server using +// the github.com/creachadair/jrpc2 package with a Websocket transport. +// +// Usage: +// go build github.com/creachadair/jrpc2/tools/examples/wshttp +// ./wshttp -listen :8080 +// +// The server accepts RPC connections on ws://
/rpc. +package main + +import ( + "context" + "flag" + "log" + "net/http" + + "github.com/creachadair/jrpc2" + "github.com/creachadair/jrpc2/handler" + "github.com/creachadair/wschannel" +) + +var listenAddr = flag.String("listen", "", "Service address") + +func main() { + flag.Parse() + if *listenAddr == "" { + log.Fatal("You must provide a non-empty -listen address") + } + + lst := wschannel.NewListener(nil) + hs := &http.Server{Addr: *listenAddr, Handler: http.DefaultServeMux} + http.Handle("/rpc", lst) + go hs.ListenAndServe() + + srv := jrpc2.NewServer(handler.Map{ + "Reverse": handler.New(func(_ context.Context, ss []string) []string { + for i, j := 0, len(ss)-1; i < j; i++ { + ss[i], ss[j] = ss[j], ss[i] + j-- + } + return ss + }), + }, nil) + + ctx := context.Background() + for { + ch, err := lst.Accept(ctx) + if err != nil { + hs.Shutdown(ctx) + log.Fatalf("Accept: %v", err) + } + log.Print("Client connected") + if err := srv.Start(ch).Wait(); err != nil { + log.Printf("Server error: %v", err) + } + log.Print("Client disconnected (wave bye)") + } +}