如何在CocosCreator中使用http和WebSocket
CocosCreator版本2.3.4
一、HttpGET
Get方式,客戶端請(qǐng)求本機(jī)地址3000端口,并攜帶參數(shù)url和name,服務(wù)端收到后返回name參數(shù)。
cocos客戶端:
//訪問地址
let url = "http://127.0.0.1:3000/?url=123&name=321";
//新建Http
let xhr = new XMLHttpRequest();
//接收數(shù)據(jù)
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
var response = xhr.responseText;
console.log(response);
}
};
//錯(cuò)誤處理
xhr.onerror = function(evt){
console.log(evt);
}
//初始化一個(gè)請(qǐng)求,GET方式,true異步請(qǐng)求
xhr.open("GET", url, true);
//發(fā)送請(qǐng)求
xhr.send();
為了方便測(cè)試,在本機(jī)用nodejs搭建一個(gè)簡(jiǎn)易服務(wù)器,在收到訪問后,返回請(qǐng)求參數(shù)中的name值。
nodejs服務(wù)端:
var app = require('express')();
var http = require('http').Server(app);
app.get('/', function(req, res){
//設(shè)置允許跨域的域名,*代表允許任意域名跨域
res.header("Access-Control-Allow-Origin","*");
//允許的header類型
res.header("Access-Control-Allow-Headers","content-type");
//跨域允許的請(qǐng)求方式
res.header("Access-Control-Allow-Methods","DELETE,PUT,POST,GET,OPTIONS");
res.send(req.query.name);
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
運(yùn)行nodejs的服務(wù)器,并運(yùn)行cocos代碼,cocos中
console.log(response); //輸出為321
二、HTTPPOST
客戶端請(qǐng)求服務(wù)器,攜帶參數(shù)name,服務(wù)端收到后返回name。
cocos客戶端:
let url = "http://127.0.0.1:3000/";
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
var response = xhr.responseText;
console.log(response);
}
};
xhr.onerror = function(evt){
console.log(evt);
}
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("name=123");
nodejs服務(wù)端:
var app = require('express')();
var http = require('http').Server(app);
var querystring = require('querystring');
app.post('/', function(req, res){
//設(shè)置允許跨域的域名,*代表允許任意域名跨域
res.header("Access-Control-Allow-Origin","*");
//允許的header類型
res.header("Access-Control-Allow-Headers","content-type");
//跨域允許的請(qǐng)求方式
res.header("Access-Control-Allow-Methods","DELETE,PUT,POST,GET,OPTIONS");
var body = "";
req.on('data', function (chunk) {
body += chunk; //一定要使用+=,如果body=chunk,因?yàn)檎?qǐng)求favicon.ico,body會(huì)等于{}
console.log("chunk:",chunk);
});
req.on('end', function () {
body = querystring.parse(body);
console.log("body:",body);
res.send(body.name);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
cocos輸出
console.log(response); //輸出123
三、WebSocket
cocos客戶端代碼:
連接本地服務(wù)器127.0.0.1:8001,連接成功后發(fā)送一段字符串,并將接收的字符串打印
let ws = new WebSocket("ws://127.0.0.1:8001");
ws.onopen = function (event) {
console.log("Send Text WS was opened.");
};
ws.onmessage = function (event) {
console.log("response text msg: " + event.data);
};
ws.onerror = function (event) {
console.log("Send Text fired an error");
};
ws.onclose = function (event) {
console.log("WebSocket instance closed.");
};
setTimeout(function () {
if (ws.readyState === WebSocket.OPEN) {
console.log("WebSocket start send message.");
ws.send("Hello WebSocket, I'm a text message.");
}
else {
console.log("WebSocket instance wasn't ready...");
}
}, 3000);
nodejs服務(wù)端:
接收字符串成功后,打印接收的數(shù)據(jù),并返回一段字符串。
var ws = require("nodejs-websocket");
console.log("開始創(chuàng)建websocket");
var server = ws.createServer(function(conn){
console.log("連接成功");
conn.on("text", function (obj) {
console.log("接收:",obj);
conn.send("message come from server");
})
conn.on("close", function (code, reason) {
console.log("關(guān)閉連接")
});
conn.on("error", function (code, reason) {
console.log("異常關(guān)閉")
});
}).listen(8001)
console.log("開始創(chuàng)建websocket完畢");
測(cè)試結(jié)果,客戶端瀏覽器輸出:

nodejs端輸出:

四、移植Egret的http和websocket到cocos
因?yàn)閏ocos沒有封裝工具類,所以直接從Egret移植http和websocket到cocos中使用,還算方便。

以上就是Cocos Creator 的Http和WebSocke的詳細(xì)內(nèi)容,更多關(guān)于Cocos Creator的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
JavaScript中使用replace結(jié)合正則實(shí)現(xiàn)replaceAll的效果
JavaScript?中使用?replace?達(dá)到?replaceAll的效果,其實(shí)就用利用的正則的全局替換。2010-06-06
javascript實(shí)現(xiàn)checkbox全選的代碼
本文給大家分享的是js實(shí)現(xiàn)checkbox的全選的代碼,在網(wǎng)頁(yè)制作中很常用的js代碼,供大家學(xué)習(xí)參考。2015-04-04
利用layer實(shí)現(xiàn)表單完美驗(yàn)證的方法
今天小編就為大家分享一篇利用layer實(shí)現(xiàn)表單完美驗(yàn)證的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-09-09

