我正在尝试使用 Go 发送 JSON 消息。这是服务器代码:
func (network *Network) Join(
w http.ResponseWriter,
r *http.Request) {
//the request is not interesting
//the response will be a message with just the clientId value set
log.Println("client wants to join")
message := Message{-1, -1, -1, ClientId(len(network.Clients)), -1, -1}
var buffer bytes.Buffer
enc := json.NewEncoder(&buffer)
err := enc.Encode(message)
if err != nil {
fmt.Println("error encoding the response to a join request")
log.Fatal(err)
}
fmt.Printf("the json: %s\n", buffer.Bytes())
fmt.Fprint(w, buffer.Bytes())
}
Run Code Online (Sandbox Code Playgroud)
网络是一个自定义结构。在主函数中,我创建了一个网络对象并将它的方法注册为对 http.HandleFunc(...) 的回调
func main() {
runtime.GOMAXPROCS(2)
var network = new(Network)
var clients = make([]Client, 0, 10)
network.Clients = clients
log.Println("starting the server")
http.HandleFunc("/request", network.Request)
http.HandleFunc("/update", network.GetNews)
http.HandleFunc("/join", network.Join)
log.Fatal(http.ListenAndServe("localhost:5000", nil))
}
Run Code Online (Sandbox Code Playgroud)
Message 也是一个结构体。它有六个字段,所有字段都是 int 的类型别名。当客户端向 url "localhost:5000/join" 发送 http GET 请求时,应该会发生这种情况
客户端比较简单。它具有完全相同的 Message 结构代码。在主函数中,它只是向“localhost:5000/join”发送 GET 请求并尝试解码响应。这是代码
func main() {
// try to join
var clientId ClientId
start := time.Now()
var message Message
resp, err := http.Get("http://localhost:5000/join")
if err != nil {
log.Fatal(err)
}
fmt.Println(resp.Status)
dec := json.NewDecoder(resp.Body)
err = dec.Decode(&message)
if err != nil {
fmt.Println("error decoding the response to the join request")
log.Fatal(err)
}
fmt.Println(message)
duration := time.Since(start)
fmt.Println("connected after: ", duration)
fmt.Println("with clientId", message.ClientId)
}
Run Code Online (Sandbox Code Playgroud)
我已经启动了服务器,等待了几秒钟,然后运行了客户端。这是结果
这个错误信息真的让我很困惑。毕竟,在我的 json 中没有任何地方,只有数字 3。所以我在客户端上导入了 io/ioutil 并使用此代码打印了响应
b, _ := ioutil.ReadAll(resp.Body)
fmt.Printf("the json: %s\n", b)
Run Code Online (Sandbox Code Playgroud)
请注意,打印语句与服务器上的相同。我希望看到我编码的 JSON。相反,我得到了这个
我是新手,不知道我这样做是否正确。但似乎上面的代码只是打印了字节片。奇怪的是,在服务器上,输出被转换为字符串。
我的猜测是我以某种方式读取了错误的数据,或者消息在服务器和客户端之间的途中被破坏了。但老实说,这些只是疯狂的猜测。
在您的服务器中,而不是
fmt.Fprint(w, buffer.Bytes())
Run Code Online (Sandbox Code Playgroud)
你需要使用:
w.Write(buffer.Bytes())
Run Code Online (Sandbox Code Playgroud)
fmt 包将 Bytes() 格式化为人类可读的切片,其中字节表示为整数,如下所示:
[123 34 87 104 97 116 ... etc
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2199 次 |
| 最近记录: |