Cocos Creator 的Http和WebSocket(移植

2021-03-15  本文已影响0人  程序猿TODO

版本2.3.4

参考:

cocos教程:网络接口

MDN Docs:XMLHttpRequest

貌似cocos creator并没有自己封装http和websocket ,所以我在API文档里搜索关键字"http"和"websocket"啥也搜不着。

一 Http Get

二 Http Post

三 WebSocket

四 移植Egret封装好的http和websocket到cocos中使用

一 Http GET

Get方式,客户端请求本机地址3000端口,并携带参数url和name,服务端收到后返回name参数。

cocos客户端:

  //访问地址
 let  url =   "http://127.0.0.1:3000/?url=123&name=321"  ; 
 //新建Http 
 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); 
 } 
 //初始化一个请求,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

二 HTTP POST

客户端请求服务器,携带参数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中使用,还算方便。

上一篇下一篇

猜你喜欢

热点阅读