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

Golang server, how to receive TCP JSON packet?

我是 Golang 的新手,我在这里使用 "Server" 代码作为起点: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 main

import (
  "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)
}

您可以将 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()

}