通过开放的TCP套接字回复一个JSON

huangapple go评论86阅读模式
英文:

Replying with a JSON on an open TCP socket

问题

以下是翻译好的内容:

我有一个服务器成功地与第二个服务器建立了连接。第二个服务器执行一个操作,我试图让它通过同一连接回复给第一个服务器一个JSON。

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 response")
		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())
		
	}
}

我在conn.Write(c)这一行上得到以下错误:

无法将类型为NewContainerJSON的c作为conn.Write的参数类型[]byte使用

两个问题:

1:这个错误具体是什么意思?它似乎在使用conn.Write函数时抱怨c不能作为字节使用,但是json.Encoder不应该将JSON转换为conn.Write可以使用的格式吗?

2:我如何使用打开的连接将JSON返回给第一个服务器?

英文:

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?

答案1

得分: 4

encoder在这一行将c的JSON编码写入到conn中:

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

这就是你需要做的全部。删除对conn.Write(c)的调用。

错误信息告诉你,c的值不能作为Write的参数使用,因为类型不匹配。NewContainerJSON不是[]byte类型。

英文:

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.

答案2

得分: 0

你首先通过以下方式将字符串写入连接:

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

这在客户端方面容易出错。在使用json解码器之前,你需要确保读取了完全相同数量的数据。

如果一个连接用于json通信,那么该流上的所有消息都应该是json格式的。
因此,如果你想发送一个通知消息,也需要对该消息进行编码:

encoder.Encode(string(resp))
英文:

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

huangapple
  • 本文由 发表于 2016年4月1日 04:55:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/36343609.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定