Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang server, how to receive TCP JSON packet?

Tags:

json

tcp

go

sockets

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)
}
like image 376
Joseph Smitty Avatar asked May 12 '15 11:05

Joseph Smitty


People also ask

How do I read JSON data in Golang?

json is read with the ioutil. ReadFile() function, which returns a byte slice that is decoded into the struct instance using the json. Unmarshal() function. At last, the struct instance member values are printed using for loop to demonstrate that the JSON file was decoded.

What is JSON go?

JSON (JavaScript Object Notation) is a simple data interchange format. Syntactically it resembles the objects and lists of JavaScript. It is most commonly used for communication between web back-ends and JavaScript programs running in the browser, but it is used in many other places, too.


1 Answers

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

}
like image 139
Not_a_Golfer Avatar answered Oct 16 '22 18:10

Not_a_Golfer