quick-cocos客户端程序:
local MainScene = class("MainScene", function()
return display.newScene("MainScene")
end)
local info={
hero={
name="zhanshen",level=2,hp=500
},
pet={
name="wind",hp=100,attack=200
}
}
function MainScene:ctor()
function onRequestFinished(event)
local ok = (event.name == "completed")
local request = event.request
if not ok then
-- 请求失败,显示错误代码和错误消息
print(request:getErrorCode(), request:getErrorMessage())
return
end
local code = request:getResponseStatusCode()
if code ~= 200 then
-- 请求结束,但没有返回 200 响应代码
print(code)
return
end
-- 请求成功,显示服务端返回的内容
local resdata=request:getResponseData()
resdata=json.decode(resdata)
print(resdata)
dump(resdata)
end
-- 创建一个请求,并以 POST 方式发送数据到服务端
local url = "http://10.12.15.70:8080/test"
local request = network.createHTTPRequest(onRequestFinished, url, "POST")
-- for k,v in pairs(info) do
-- for k,v in pairs(v) do
-- request:addPOSTValue(k,v)
-- end
-- end
local js=json.encode(info)
request:setPOSTData(js)
-- 开始请求。当请求完成时会调用 callback() 函数
request:start()
end
function MainScene:onEnter()
end
function MainScene:onExit()
end
return MainScene
golang服务端程序:
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
var info map[string]string
func main() {
http.HandleFunc("/test", hand)
err := http.ListenAndServe("10.12.15.70:8080", nil)
if err != nil {
fmt.Println("err")
}
}
func hand(w http.ResponseWriter, r *http.Request) {
info = make(map[string]string)
info["name"] = "server"
info["level"] = "1"
data, err := json.Marshal(info)
if err != nil {
fmt.Println(err)
}
fmt.Println("ok")
//w.Write([]byte("connect ok"))
w.Write(data)
// r.ParseForm() //解析参数, 默认是不会解析的
// fmt.Println(r.Form) //这些是服务器端的打印信息
// fmt.Println("path", r.URL.Path)
// fmt.Println("scheme", r.URL.Scheme)
// fmt.Println(r.Form["url_long"])
// for k, v := range r.Form {
// fmt.Println("key:", k)
// fmt.Println("val:", v) //v的类型是[]string
// }
defer r.Body.Close()
body, err := ioutil.ReadAll(r.Body) //读取服务器返回的信息
if err != nil {
fmt.Println("read err")
}
fmt.Println(body)
fmt.Println(string(body))
var tmp interface{} //解码未知格式的json数据
json.Unmarshal(body, &tmp)
fmt.Println(tmp)
}
记得把IP地址改成自己的
有疑问加站长微信联系(非本文作者)