-
-
Save smallnest/3c50640cedc8d9fba33e25f13dc608bf to your computer and use it in GitHub Desktop.
Golang Websocket JSONRPC server and client
This file contains hidden or 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 hidden or 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