doutan4831 2015-05-12 11:56
浏览 508
已采纳

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

I'm new to Golang and am using the "Server" code here as a starting point: http://www.golang-book.com/13/index.htm#section7

I've attempted to use JSON instead of Gob decoding (since I am required to write the client in C#), and I'm sending the JSON TCP data client data in a separate script from the code below.

I'm stuck on the part where I'm actually receiving the JSON TCP data and storing it in a variable for it to be decoded. It looks like I can decode it with json.Unmarshal, but I can't find any examples where json.Unmarshal is being used to decode TCP data. I can only find examples where json.Unmarshal is being used to decode JSON strings.

My code is below:

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

Stuck on the line below. What could I set the rawJSON variable equal to?

  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条回答 默认 最新

  • duangan6636 2015-05-12 12:54
    关注

    You can patch a json.Decoder directly to the connection:

    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()
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧