这篇文章主要介绍了怎么在CocosCreator中使用http和WebSocket,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
CocosCreator版本2.3.4
一、HttpGET
Get方式,客户端请求本机地址3000端口,并携带参数url和name,服务端收到后返回name参数。
cocos客户端:
//访问地址let url = "http://127.0.0.1:3000/?url=123&name=321";//新建Httplet 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);}//初始化一个请求,GET方式,true异步请求xhr.open("GET", url, true);//发送请求xhr.send();
为了方便测试,在本机用nodejs搭建一个简易服务器,在收到访问后,返回请求参数中的name值。
nodejs服务端:
var app = require('express')(); var http = require('http').Server(app); app.get('/', function(req, res){ //设置允许跨域的域名,*代表允许任意域名跨域 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的服务器,并运行cocos代码,cocos中
console.log(response); //输出为321
二、HTTPPOST
客户端请求服务器,携带参数name,服务端收到后返回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服务端:
var app = require('express')(); var http = require('http').Server(app); var querystring = require('querystring'); app.post('/', function(req, res){ //设置允许跨域的域名,*代表允许任意域名跨域 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客户端代码:
连接本地服务器127.0.0.1:8001,连接成功后发送一段字符串,并将接收的字符串打印
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服务端:
接收字符串成功后,打印接收的数据,并返回一段字符串。
var ws = require("nodejs-websocket"); console.log("开始创建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("关闭连接") }); conn.on("error", function (code, reason) { console.log("异常关闭") });}).listen(8001)console.log("开始创建websocket完毕");
测试结果,客户端浏览器输出:
nodejs端输出:
四、移植Egret的http和websocket到cocos
因为cocos没有封装工具类,所以直接从Egret移植http和websocket到cocos中使用,还算方便。
感谢你能够认真阅读完这篇文章,希望小编分享的“怎么在CocosCreator中使用http和WebSocket”这篇文章对大家有帮助,同时也希望大家多多支持编程网,关注编程网行业资讯频道,更多相关知识等着你来学习!