golang send and receive objects

huangapple go评论80阅读模式
英文:

golang send and receive objects

问题

我能够使用以下代码在 Golang 中发送和接收字符串:

// 发送端
message.Buf.WriteTo(conn)

// 接收端
message, err := bufio.NewReader(conn).ReadString('\n')
if err != nil {
panic(err)
}
fmt.Print("来自客户端的消息:", string(message))

然而,我想要发送整个 message 对象并在接收端接收它。

类似这样:

// 发送端
message.WriteTo(conn)

// 接收端
message, err := bufio.NewReader(conn).ReadMessageObject()

我对 Golang 还很陌生,任何指导都将非常有帮助。

英文:

I am able to send and receive strings in golang using the following code:

//send side
message.Buf.WriteTo(conn)

//receive side
message, err := bufio.NewReader(conn).ReadString('\n')
    if err != nil {
        panic(err)
    }
fmt.Print("Message from client: ", string(message))

However, I would like to send the entire message object and receive it at the receive side

Something like:

//send side
message.WriteTo(conn)

//receive side
message,err :=bufio.NewReader(conn).ReadMessageObject()

I am new to Golang and any pointers are extremely helpful.

答案1

得分: 2

你首先需要为你的消息声明一个类型。类似这样:

type Message struct {
    From      string
    To        string
    Text      string
    CreatedAt time.Time
}

然后,你需要决定如何将你的新类型编码为字节,以及如何从字节解码,因为你只能通过字节发送数据。
你可以选择将消息以 JSONXML 或者 gob 等形式发送。选择哪种方式取决于你的需求,json 是普遍使用且可读性较好的方式,而 gob 则更快,至少我听说是这样的,我自己还没有真正使用过 gob

例如,如果你选择使用 json

// 接收
var m Message
if _, err := json.NewDecoder(conn).Decode(&m); err != nil {
    panic(err)
}

// 发送
if err := json.NewEncoder(conn).Encode(m); err != nil {
    panic(err)
}

以上是代码的翻译部分。

英文:

You'll first want to declare a type for your messages. Something like:

type Message struct {
    From      string
    To        string
    Text      string
    CreatedAt time.Time
}

Then you'll need to decide how you want your new types to be encoded to/decoded from bytes, since all you can send through the wire are bytes.
You can for example send your messages as json, as xml, or as gob, etc. Which one you choose depends on what your requirements are, json is ubiquitous and readable but gob on the other hand is much faster, at least that's what I heard, haven't really used gob myself yet.

For example if you go with json.

// receive
var m Message
if _, err := json.NewDecoder(conn).Decode(&m); err != nil {
    panic(err)
}

// send
if err := json.NewEncoder(conn).Encode(m); err != nil {
    panic(err)
}

huangapple
  • 本文由 发表于 2017年5月1日 03:23:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/43710406.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定