Skip to content

Instantly share code, notes, and snippets.

@oscardelben
Created May 1, 2013 01:27
Show Gist options
  • Save oscardelben/5493188 to your computer and use it in GitHub Desktop.
Save oscardelben/5493188 to your computer and use it in GitHub Desktop.
The coupons RPC server
package main
import (
"fmt"
"log"
"net"
"net/http"
"net/rpc"
)
type Args struct {
Id int
}
type Competition struct {
Coupons chan int
}
type Server struct {
competitions map[int]*Competition
}
var max int = 1000
var done chan bool
func (s *Server) Compute(args *Args, reply *string) error {
c := s.competitions[args.Id]
if len(c.Coupons) == 0 {
*reply = "error"
return nil
}
n := <-c.Coupons
total := args.Id*max + (n - 1)
*reply = fmt.Sprintf("%x", total)
return nil
}
func main() {
startServer()
startClient()
}
func startServer() {
server := new(Server)
server.competitions = make(map[int]*Competition, 10)
for i := 0; i < 10; i++ {
competition := new(Competition)
competition.Coupons = make(chan int, max)
for j := 0; j < max; j++ {
competition.Coupons <- j + 1
}
server.competitions[i+1] = competition
}
rpc.Register(server)
rpc.HandleHTTP()
l, e := net.Listen("tcp", ":1234")
if e != nil {
log.Fatal("listen error:", e)
}
go http.Serve(l, nil)
}
func startClient() {
done = make(chan bool)
client, err := rpc.DialHTTP("tcp", "localhost"+":1234")
if err != nil {
log.Fatal("dialing:", err)
}
fmt.Println("**Coupons for server 4**")
args := &Args{4}
for i := 0; i < max; i++ {
go func() {
var reply string
err = client.Call("Server.Compute", args, &reply)
if err != nil {
log.Fatal("compute error:", err)
}
fmt.Println("Response:", reply)
done <- true
}()
}
for i := 0; i < 1000; i++ {
<-done
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment