登录
首页 >  Golang >  Go问答

如何通过http实现google的协议缓冲区

来源:stackoverflow

时间:2024-04-01 10:09:39 164浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《如何通过http实现google的协议缓冲区》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

问题内容

我正在使用 google 的协议缓冲区将数据从客户端发送到服务器。

客户端和服务器都是用 golang 编写的。

我认为它使用纯 tcp 将数据从 client 发送到 server

示例客户端代码:

func getFakeTransaction() *proto.Transaction {
    transaction := new(proto.Transaction)
    transaction.ClientId = "client_1"
    transaction.ClientName = "Europa"

    items := new(proto.Items)
    items.ItemId = 1
    items.ItemName = "Space suite"
    items.ItemValue = 2000
    transaction.Items = items

    return transaction
}

func readDataFromExternalDatasource() *proto.Transaction {
    return getFakeTransaction()
}

func sentDataToServer(data []byte) {
    conn, err := net.Dial("tcp", "localhost:8080")
    defer conn.Close()
    if err != nil {
        fmt.Fprintf(os.Stderr, "Error while dialing server: %s\n", err.Error())
        return
    }
    sentBytes, err := conn.Write(data)
    if err != nil {
        fmt.Fprintf(os.Stderr, "Error sending bytes to serve: %s\n", err.Error())
        return
    }
    fmt.Printf("Sent %d bytes\n", sentBytes)
}

func main() {
    fmt.Println("Starting client..")
    data := readDataFromExternalDatasource()
    dataInByteArr, err := protoc.Marshal(data)
    if err != nil {
        fmt.Fprintf(os.Stderr, "Error while Marshal data: %s", err.Error())
    }
    for {
        sentDataToServer(dataInByteArr)
        time.Sleep(1000)
    }
}

如何使用 golang 中的协议缓冲区通过 http 从客户端向服务器发送数据


解决方案


成功实现了 protobuff vai http。

鸣谢https://jacobmartins.com/2016/05/24/practical-golang-using-protobuffs/

sample_client:

func getfaketransaction() *proto.transaction {
    transaction := new(proto.transaction)
    transaction.clientid = "client_1"
    transaction.clientname = "europa"

    items := new(proto.items)
    items.itemid = 1
    items.itemname = "space suite"
    items.itemvalue = 2000
    transaction.items = items

    return transaction
}

func sendmessage(transaction *proto.transaction) {
    message, err := protoc.marshal(transaction)
    if err != nil {
        fmt.fprintf(os.stderr, "error while marshaling message: %s", err.error())
        os.exit(1)
    }

    _, err = http.post("http://localhost:8080", "", bytes.newbuffer(message))
    if err != nil {
        fmt.fprintf(os.stderr, "error while post request to server: %s", err.error())
        os.exit(1)
    }
    fmt.printf("sent %d bytes to server\n", len(message))
}

func main() {
    fmt.println("starting client..")
    transaction := getfaketransaction()
    for {
        sendmessage(transaction)
        // time.sleep(1 * time.second)
    }
}

示例服务器:

func printmessage(t *proto.transaction) {
    clientid := t.getclientid()
    clientname := t.getclientname()
    items := t.getitems()
    fmt.printf("clientid: %s, clientname: %s, items: %s\n", clientid, clientname, items)
}

func main() {
    fmt.println("staring server..")
    http.handlefunc("/", func(w http.responsewriter, r *http.request) {
        message, err := ioutil.readall(r.body)
        if err != nil {
            fmt.fprintf(os.stderr, "error while reading data from client: ", err.error())
            return
        }
        transaction := new(proto.transaction)
        // protoc.unmarshal(message, &transaction)
        if err = transaction.xxx_unmarshal(message); err != nil {
            fmt.fprintf(os.stderr, "error while unmarshaling client message: %s", err.error())
            return
        }
        printmessage(transaction)
    })
    http.listenandserve(":8080", nil)

}

示例原型文件:

syntax="proto3";

package proto;

enum Status {
    SUCCESS = 0;
    INPROGRESS = 1;
    FAILED = 2;
}

message Items {
    int32 itemId = 1;
    string itemName = 2;
    int32 itemValue = 3;
    Status status = 4;
}

message Transaction {
    string clientId = 1;
    string clientName = 2;
    Items items = 3;
}

今天关于《如何通过http实现google的协议缓冲区》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>