Last active
October 11, 2024 01:43
-
-
Save mowings/dad4917b6fc21e6e5ffe2da3b16e7ef9 to your computer and use it in GitHub Desktop.
Golang Websocket JSONRPC server and client
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 ( | |
"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) | |
} |
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 ( | |
"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
thanks, I used the
github.com/gorilla/websocket
, annother demo:https://gist.github.com/zhangguanzhang/d046401a168596a2d3f195a2f628fb9c