Skip to content

Instantly share code, notes, and snippets.

@mowings
Last active February 29, 2024 08:09
Show Gist options
  • Star 24 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save mowings/dad4917b6fc21e6e5ffe2da3b16e7ef9 to your computer and use it in GitHub Desktop.
Save mowings/dad4917b6fc21e6e5ffe2da3b16e7ef9 to your computer and use it in GitHub Desktop.
Golang Websocket JSONRPC server and client
package main
import (
"golang.org/x/net/websocket"
"log"
"net/rpc/jsonrpc"
)
// In a real project, these would be defined in a common file
type Args struct {
A int
B int
}
type Arith int
func main() {
origin := "http://localhost/"
url := "ws://localhost:7000/ws"
ws, err := websocket.Dial(url, "", origin)
if err != nil {
log.Fatal(err)
}
defer ws.Close()
args := Args{7, 8}
var reply int
c := jsonrpc.NewClient(ws)
err = c.Call("Arith.Multiply", args, &reply)
if err != nil {
log.Fatal("arith error:", err)
}
log.Printf("Arith: %d*%d=%d", args.A, args.B, reply)
}
package main
import (
"golang.org/x/net/websocket"
"log"
"net/http"
"net/rpc"
"net/rpc/jsonrpc"
)
// In a real project, these would be defined in a common file
type Args struct {
A int
B int
}
type Arith int
func (t *Arith) Multiply(args *Args, reply *int) error {
*reply = args.A * args.B
return nil
}
func main() {
rpc.Register(new(Arith))
http.Handle("/ws", websocket.Handler(serve))
http.ListenAndServe("localhost:7000", nil)
}
func serve(ws *websocket.Conn) {
log.Printf("Handler starting")
jsonrpc.ServeConn(ws)
log.Printf("Handler exiting")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment