使用确认向主机集发送消息

时间:2013-01-06 07:00:43

标签: go rpc

功能如下:

func Message(worker_ID int, message string, args *Args , reply *int) chan bool {
}

此功能驻留在主机上,当客户端想要将消息发送给主机时,主机位于不同的位置,因此发送消息需要IP和端口吗?哪种机制可以有用net.dial()gobrpc

2 个答案:

答案 0 :(得分:2)

如果你想要一些简单的东西,那么看看net/rpc将gob和网络包装到一个远程过程调用框架中,它应该做你想要的。

服务器

从文档中运行HTTP服务器

type Args struct {
        A, B int
}

type Arith int

func (t *Arith) Multiply(args *Args, reply *int) error {
        *reply = args.A * args.B
        return nil
}

arith := new(Arith)
rpc.Register(arith)
rpc.HandleHTTP()
l, e := net.Listen("tcp", ":1234")
if e != nil {
        log.Fatal("listen error:", e)
}
go http.Serve(l, nil)

<强>客户端

此时,客户端可以使用方法“Arith.Multiply”查看服务“Arith”。要调用一个,请拨打服务器然后拨打电话。您也可以在结果返回通道的位置进行异步调用。

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

args := &server.Args{7,8}
var reply int
err = client.Call("Arith.Multiply", args, &reply)
if err != nil {
        log.Fatal("arith error:", err)
}
fmt.Printf("Arith: %d*%d=%d", args.A, args.B, reply)

框架有点奇怪的是每个远程调用只能有一个输入参数和一个输出参数,这意味着你需要将所有参数包装在struct中。

答案 1 :(得分:1)

// server.go将提供用于通信和处理主机的接口

// workerDead(消息字符串),发送消息并等待确认,如果没有确认意味着工人死亡

package
main
import(

"fmt"
"io"
"net"
"net/http"
"net/rpc"
"path"
"os"
)

type Flag int
type Args struct{
message string
}
func main() {

flag := new(Flag)
rpc.Register(flag)
rpc.HandleHTTP()
err := http.ListenAndServe(":1234", nil) //ListenAndServe starts an HTTP server with a given address and handler.
//The handler is usually nil, which means to use DefaultServeMux.
if err != nil {
fmt.Println(err.Error())
}
}

//Worker counts the number of hosts
func workerCount() int
{
return db.runCommand( { count: 'id' } ) //mongodb command to count the id
}

// Returns an array of the distinct values of field id from all documents in the workers collection
//In mongodb document is analogous to rdbms table and collection is record

func Worker(worker int) []string{
return db.runCommand ({ distinct: 'workers', key: 'id' } ) //mongodb command to get the array of list of
//workers for column id
}

func Message(worker int, message string, args *Args , reply *int) chan bool {


server, err :=rpc.Dial("tcp","192.168.23.12") //Serve Dials here to send message to host, IP address here is of host
if(err!=nil){
log.Fatal("Dialing", err)
}
var reply bool
args:=Args{message};
err = server.Call(args,&reply);
if(err!=nil){
log.Fatal("Dialing", err)
replaceWorker(); // No reply from worker then call to replace worker
}
fmt.Println("Reply from host", reply);

}
return nil
}
//Replace dead worker of particular project with fresh worker
func replaceWorker(worker_id int,project_id int)
{
db.workers.update( //this query updates workers collection with id=worker_id(id of dead worker)
   { _id: worker_id, _project_id: project_id },
   {
     //$set: { ' ': 'Warner' },
   }

)

}