Commit 4629178a authored by Boris Mühmer's avatar Boris Mühmer
Browse files

imported example from pkg docs and made it run

parent 9085abea
Loading
Loading
Loading
Loading
Loading

cmd/rec/main.go

0 → 100644
+42 −0
Original line number Diff line number Diff line
package main

import (
	"fmt"
	"log"
	"net/rpc"

	"repositories.muehmer.net/bsmrgo/rpctest/pkg/rpcexamplelib"
)

const serverAddress = "localhost"

func main() {
	client, err := rpc.DialHTTP("tcp", serverAddress+":1234")
	if err != nil {
		log.Fatal("dialing:", err)
	}

	args := &rpcexamplelib.Args{A: 21, B: 8}

	callSync(client, args)
	callAsync(client, args)
}

func callSync(client *rpc.Client, args *rpcexamplelib.Args) {
	var reply int
	err := client.Call("Arith.Multiply", args, &reply)
	if err != nil {
		log.Fatal("arith error:", err)
	}
	fmt.Printf("Arith: %d*%d = %d\n", args.A, args.B, reply)
}

func callAsync(client *rpc.Client, args *rpcexamplelib.Args) {
	quotient := new(rpcexamplelib.Quotient)
	divCall := client.Go("Arith.Divide", args, quotient, nil)
	replyCall := <-divCall.Done
	if replyCall.Error != nil {
		log.Fatal(replyCall.Error)
	}
	fmt.Printf("Arith: %d/%d => quo:%d, rem:%d\n", args.A, args.B, quotient.Quo, quotient.Rem)
}

cmd/res/main.go

0 → 100644
+21 −0
Original line number Diff line number Diff line
package main

import (
	"log"
	"net"
	"net/http"
	"net/rpc"

	"repositories.muehmer.net/bsmrgo/rpctest/pkg/rpcexamplelib"
)

func main() {
	arith := new(rpcexamplelib.Arith)
	rpc.Register(arith)
	rpc.HandleHTTP()
	l, e := net.Listen("tcp", ":1234")
	if e != nil {
		log.Fatal("listen error:", e)
	}
	http.Serve(l, nil)
}
+1 −0
Original line number Diff line number Diff line
package rpcexamplelib
+27 −0
Original line number Diff line number Diff line
package rpcexamplelib

import "errors"

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
}