David Monaghan
David Monaghan

Reputation: 43

Replying with a JSON on an open TCP socket

I have a server that successfully opens a connection with a second server. The second server performs an action and I am trying to get it to reply to the first server with a JSON on the same connection.

package main

import (
    "fmt"
    "net"
    "encoding/json"
)

type NewContainerJSON struct {
    Action string           `json:"Action"`
    ContainerName string    `json:"ContainerName"`
    BaseServer string       `json:"BaseServer"`
    CMS string              `json:"CMS"`
    WebsiteName string      `json:"WebsiteName"`
    DBrootPWD string        `json:"DBrootPWD"`
    DBadminUname string     `json:"DBadminUname"`
    DBadminPWD string       `json:"DBadminPWD"`
}

func main() {

    service := "127.0.0.1:8081"
    tcpAddr, err := net.ResolveTCPAddr("tcp", service)
    checkError(err)

    listener, err := net.ListenTCP("tcp", tcpAddr)
    checkError(err)

    conn, err := listener.Accept()
    checkError(err)

    decoder := json.NewDecoder(conn)
    encoder := json.NewEncoder(conn)

    var b NewContainerJSON
    err = decoder.Decode(&b)
    checkError(err)
    fmt.Println(b.Action)

    if b.Action == "createNew" {
        fmt.Println("This works")
        resp := []byte("And here's our repomse")
        conn.Write(resp)

        c := NewContainerJSON {
            Action: "createdNewContainer",
            ContainerName: "Test",
            BaseServer: "Test",
            CMS: "Test",
            WebsiteName: "Test",
            DBrootPWD: "Test",
            DBadminUname: "Test",
            DBadminPWD: "Test",
        }

        encoder := json.NewEncoder(conn)
        if err := encoder.Encode(c); err != nil {
            fmt.Println("encode.Encode error: ", err)
        }

        conn.Write(c)
    }
}

func checkError(err error) {
    if err != nil {
        fmt.Println("An error occurred: ", err.Error())

    }
}

I get following error on the line conn.Write(c)

cannot use c (type NewContainerJSON) as type []byte in argument to conn.Write

Two questions:

1: What exactly is this error saying? It seems to be complaining that 'c' cannot be used as a Byte when using the conn.Write function but shouldn't the json.Encoder convert the JSON to a format the conn.Write can use?

2: How exactly can I return a JSON back to the first server using the open connection?

Upvotes: 1

Views: 1653

Answers (2)

fluter
fluter

Reputation: 13786

You first write a string to the connection by

resp := []byte("And here's our repomse")
conn.Write(resp)

This will make it error-prone on the client side. You'll need to read exactly the same amount of data before employ the json decoder on this connection.

If a connection is used for json communication, all the messages on this stream should be json. So if you want send a message to notify, encode that message too:

encoder.Encode(string(resp))

Upvotes: 0

Thundercat
Thundercat

Reputation: 120941

The encoder writes the JSON encoding of c to conn on this line:

if err := encoder.Encode(c); err != nil {

That's all you need to do. Delete the call to conn.Write(c).

The error message is telling you that the value of c cannot be used as the argument to Write because of a type mismatch. A NewContainerJSON is not a []byte.

Upvotes: 4

Related Questions