2018-05-23http服务

package main

import (
    "os"
    "fmt"
    "net/http"

)

type nodeINfo struct {
    // 节点名称
    id string
    //节点路径
    path  string
    // http 相应
    write http.ResponseWriter
}
// 创建map,存储各个国家的ip地址
var nodeTable  = make(map[string]string)


func main()  {
    // 接收终端参数
    userId := os.Args[1]
    fmt.Println(userId)
    // 存储四个国家的ip地址
    nodeTable = map[string]string{
        "Apple" :"localhost:1111",
        "MS" :"localhost:1112",
        "Google" :"localhost:1113",
        "IBM" :"localhost:1114",

    }

    // 创建国家对象
    node := nodeINfo{id:userId,path:nodeTable[userId]}
// http协议的回掉函数
// http://localhost:1111/req?warTime =1111
http.HandleFunc("/req",node.request)
http.HandleFunc("/prePrepare",node.prePrepare)
    if err:=http.ListenAndServe(node.path,nil);err!=nil {
        fmt.Println(err)
    }

}
// http服务器,接收到网络请求并且。req则回掉request
func (node *nodeINfo)request(writer http.ResponseWriter,request *http.Request)  {
   // 该命令允许request请求参数
    request.ParseForm()
    if (len(request.Form["warTime"])>0) {
        node.write =writer
        fmt.Println("主节点接收到的参数信息为",request.Form["warTime"][0])
        
        // 激活主节点后向其他的节点发送广播
        node.broadcast(request.Form["warTime"][0],"/prePrepare")

    }
}
// 节点发送广播的方法
func (node *nodeINfo)broadcast(msg string,path string)  {
    fmt.Println("广播",path)
    // 遍历所有的节点
    for nodeId,url :=range nodeTable  {
        if nodeId== node.id{
            continue

        }
        // 使当前节点外的节点作出相应
        http.Get("http://"+url+path+"?warTime="+msg+"&nodeId="+node.id)


    }

}
//处理广播后接收到的数据
func (node *nodeINfo)prePrepare(writer http.ResponseWriter,request *http.Request)  {
    request.ParseForm()
    fmt.Println("接收到的广播为",request.Form["warTime"][0])

}

// 主节点是apple 会分发给其余的节点信息
// 启动一个网页服务例如http://localhost:1111/req?warTime=1111
在命令行执行
./main.go:7:2: imported and not used: "go/types"
./main.go:8:2: imported and not used: "io"
FairyMacBook-Pro:BFT zhaoran$ go build main.go
FairyMacBook-Pro:BFT zhaoran$ ./main Apple
Apple
主节点接收到的参数信息为 1111

FairyMacBook-Pro:BFT zhaoran$ go build main.go

command-line-arguments

./main.go:8:2: imported and not used: "io"
FairyMacBook-Pro:BFT zhaoran$ go build main.go
FairyMacBook-Pro:BFT zhaoran$ ./main Apple
Apple
主节点接收到的参数信息为 1111
广播 /prePrepare
其余的节点执行:
Last login: Wed May 23 14:15:12 on ttys000
FairyMacBook-Pro:BFT zhaoran$ ./main MS
MS
接收到的广播为 1111

/*
其余的相当于执行如下代码
go build main.go

./main Apple

./main IBM

./main MS

./main Google
开了四个服务器
*/


image.png

主服务器分发图:

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容