Fragment Description:



Package jsonrpc implements a JSON-RPC ClientCodec and ServerCodec for the rpc package Example:
JSON Arith Server, try it with 'rpcJSONclient.go' Start the server, then open a new terminal and type:
'go run rpcJSONClient.go localhost:1234' You should see the expected ouptput.

rpcJSONServer

Last update, on 2015, Fri 30 Oct, 11:34:34

/* ... <== see fragment description ... */

package main

import (
    "errors"
    "fmt"
    "net"
    "net/rpc"
    "net/rpc/jsonrpc"
    "os"
)

type Args struct {
    A, B int
}
type Quotient struct {
    Quo, Rem int
}
type Arith int

func (t *Arith) Multiply(args *Args, reply *int) error {
    *reply = args.A * args.B
    return nil
}
func (t *Arith) Divide(args *Args, quo *Quotient) error {
    if args.B == 0 {
        return errors.New("divide by zero")
    }
    quo.Quo = args.A / args.B
    quo.Rem = args.A % args.B
    return nil
}
func main() {
    arith := new(Arith)
    rpc.Register(arith)
    tcpAddr, err := net.ResolveTCPAddr("tcp", ":1234")
    checkError(err)
    listener, err := net.ListenTCP("tcp", tcpAddr)
    checkError(err)
    /* This works: rpc.Accept(listener)
    */
    /* and so does this:    */
    for {
        conn, err := listener.Accept()
        if err != nil {
            continue
        }
        jsonrpc.ServeConn(conn)
    }
}
func checkError(err error) {
    if err != nil {
        fmt.Println("Fatal error ", err.Error())
        os.Exit(1)
    }
}

/* Expected Output:
Arith: 17*8=136
Arith: 17/8=2 remainder 1
*/



Comments