如何在CocosCreator中使用http和WebSocket
CocosCreator版本2.3.4
一、HttpGET
Get方式,客戶端請求本機地址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);
}
};
//錯誤處理
xhr.onerror = function(evt){
console.log(evt);
}
//初始化一個請求,GET方式,true異步請求
xhr.open("GET", url, true);
//發(fā)送請求
xhr.send();
為了方便測試,在本機用nodejs搭建一個簡易服務(wù)器,在收到訪問后,返回請求參數(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");
//跨域允許的請求方式
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');
});
運行nodejs的服務(wù)器,并運行cocos代碼,cocos中
console.log(response); //輸出為321
二、HTTPPOST
客戶端請求服務(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");
//跨域允許的請求方式
res.header("Access-Control-Allow-Methods","DELETE,PUT,POST,GET,OPTIONS");
var body = "";
req.on('data', function (chunk) {
body += chunk; //一定要使用+=,如果body=chunk,因為請求favicon.ico,body會等于{}
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完畢");
測試結(jié)果,客戶端瀏覽器輸出:

nodejs端輸出:

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

以上就是Cocos Creator 的Http和WebSocke的詳細內(nèi)容,更多關(guān)于Cocos Creator的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
JavaScript常見事件處理程序?qū)嵗偨Y(jié)
這篇文章主要介紹了JavaScript常見事件處理程序,結(jié)合實例形式總結(jié)分析了javascript HTML事件、DOM事件、IE事件等相關(guān)處理程序與操作技巧,需要的朋友可以參考下2019-01-01
動態(tài)創(chuàng)建樣式表在各瀏覽器中的差異測試代碼
對于標準瀏覽器,直接使用css.innerHTML也可以修改HTMLStyleElement的css規(guī)則2011-09-09
IE6下javasc#ipt:void(0) 無效的解決方法
本篇文章主要是對IE6下javasc#ipt:void(0) 無效的解決方法進行了介紹,需要的朋友可以過來參考下,希望對大家有所幫助2013-12-12
js調(diào)用父框架函數(shù)與彈窗調(diào)用父頁面函數(shù)的簡單方法
下面小編就為大家?guī)硪黄猨s調(diào)用父框架函數(shù)與彈窗調(diào)用父頁面函數(shù)的簡單方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-11-11
Javascript中的return作用及javascript return關(guān)鍵字用法詳解
本文給大家介紹Javascript中的return作用及javascript return關(guān)鍵字用法詳解,對于大家學習javascript中的return知識有所幫助,感興趣的朋友一起學習吧2015-11-11

