为了账号安全,请及时绑定邮箱和手机立即绑定

Golang服务器,如何接收TCP JSON数据包?

Golang服务器,如何接收TCP JSON数据包?

Go
精慕HU 2021-10-04 17:21:39
我是 Golang 的新手,在这里使用“服务器”代码作为起点:http : //www.golang-book.com/13/index.htm#section7我尝试使用 JSON 而不是 Gob 解码(因为我需要用 C# 编写客户端),并且我将 JSON TCP 数据客户端数据与下面的代码分开发送。我被困在我实际接收 JSON TCP 数据并将其存储在变量中以便对其进行解码的部分。看起来我可以用 解码它json.Unmarshal,但我找不到任何json.Unmarshal用于解码 TCP 数据的示例。我只能找到json.Unmarshal用于解码 JSON 字符串的示例。我的代码如下:package mainimport (  "encoding/json"  "fmt"  "net")type coordinate struct {  X float64 `json:"x"`  Y float64 `json:"y"`  Z float64 `json:"z"`}func server() {  // listen on a port  ln, err := net.Listen("tcp", ":9999")  if err != nil {    fmt.Println(err)    return  }  for {    // accept a connection    c, err := ln.Accept()    if err != nil {      fmt.Println(err)      continue    }    // handle the connection    go handleServerConnection(c)  }}func handleServerConnection(c net.Conn) {  // receive the message  var msg coordinate卡在下面的线上。我可以将 rawJSON 变量设置为等于什么?  err := json.Unmarshal([]byte(rawJSON), &msg)  if err != nil {    fmt.Println(err)  } else {    fmt.Println("Received", msg)  }  c.Close()}func main() {  go server()  //let the server goroutine run forever  var input string  fmt.Scanln(&input)}
查看完整描述

1 回答

?
收到一只叮咚

TA贡献1821条经验 获得超4个赞

您可以json.Decoder直接修补连接:


func handleServerConnection(c net.Conn) {


    // we create a decoder that reads directly from the socket

    d := json.NewDecoder(c)


    var msg coordinate


    err := d.Decode(&msg)

    fmt.Println(msg, err)


    c.Close()


}


查看完整回答
反对 回复 2021-10-04
  • 1 回答
  • 0 关注
  • 328 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信