Golang server how to get TCP JSON packet?

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

I tried using JSON instead of Gob decoding (since I need to write the client in C #) and I am sending the client JSON TCP data to a separate script from the code below.

I am stuck on the part where I actually get JSON TCP data and store it in a variable to decode it. It looks like I can decode it using json.Unmarshal

, but I can't find examples where it is json.Unmarshal

used to decode TCP data. I can find examples where it is json.Unmarshal

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 can I set the rawJSON variable to equal?

  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)
}

      

+3


source to share


1 answer


You can fix 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()

}

      

+8


source







All Articles