first tries

This commit is contained in:
Radu Ioan Fericean
2012-01-24 16:59:42 +02:00
parent 93446afa3d
commit a61556094a
4 changed files with 108 additions and 17 deletions

3
.gitignore vendored Normal file
View File

@@ -0,0 +1,3 @@
*.a
*.6
bin/*

View File

@@ -1,17 +0,0 @@
package main
import (
"flag"
"fmt"
"log"
)
var (
host = flag.String("host", "localhost:8080", "target host:port")
)
func main() {
flag.Parse()
fmt.Println(*host)
log.Print("Bye!")
}

62
src/cmd/inquirer.go Normal file
View File

@@ -0,0 +1,62 @@
package main
import (
"fmt"
"log"
"net/rpc"
"net/http"
"time"
)
type RaterList struct {
clients map[string]*rpc.Client
}
var raterList *RaterList
func (rl *RaterList) RegisterRater(clientAddress string, replay *byte) error {
time.Sleep(1 * time.Second) // wait a second for Rater to start serving
client, err := rpc.DialHTTP("tcp", clientAddress)
if err != nil {
log.Panic("Could not connect to client!")
}
rl.clients[clientAddress] = client
log.Print(fmt.Sprintf("Server %v registered succesfully", clientAddress))
return nil
}
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "<html><body><ol>")
for addr, _ := range raterList.clients {
fmt.Fprint(w, fmt.Sprintf("<li>%s</li>", addr))
}
fmt.Fprint(w, "</ol></body></html>")
}
func callRater(rl *RaterList){
var reply float64
arg := 9.0
log.Print("Starting client polling.")
for{
for addr,client := range rl.clients {
err := client.Call("Sumer.Square", arg, &reply)
if err != nil {
log.Print("Closing client!")
delete(rl.clients, addr)
}
fmt.Println(fmt.Sprintf("Result from rater(%v): %v", addr, reply))
}
time.Sleep(5 * time.Second)
}
}
func main() {
raterList = &RaterList{clients: make(map[string] *rpc.Client)}
go callRater(raterList)
rpc.Register(raterList)
rpc.HandleHTTP()
http.HandleFunc("/", handler)
log.Print("The server is listening...")
http.ListenAndServe(":2000", nil)
}

43
src/cmd/rater.go Normal file
View File

@@ -0,0 +1,43 @@
package main
import (
"net/rpc"
"net/http"
"math"
"log"
"flag"
)
var (
server = flag.String("server", "127.0.0.1:2000", "target host:port")
listen = flag.String("listen", "127.0.0.1:1234", "target host:port")
)
type Sumer int
func (t *Sumer) Square(n float64, reply *float64) error {
*reply = math.Sqrt(n)
return nil
}
func registerToServer(){
client,err := rpc.DialHTTP("tcp", *server)
if err != nil {
log.Panic("Cannot register to server!")
}
var reply byte
log.Print("Registering to server ", *server)
client.Call("RaterList.RegisterRater", *listen, &reply)
if err := client.Close(); err != nil {
log.Panic("Could not close server registration!")
}
}
func main() {
flag.Parse()
arith := new(Sumer)
rpc.Register(arith)
rpc.HandleHTTP()
go registerToServer()
http.ListenAndServe(*listen, nil)
}