我是 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()
}
- 1 回答
- 0 关注
- 328 浏览
添加回答
举报
0/150
提交
取消