如何在CocosCreator中使用http和WebSocket

本文介绍了如何在CocosCreator2.3.4中使用HttpGET和HTTPPOST方法进行客户端与Node.js服务器的数据交互,包括设置跨域和参数传递。同时展示了WebSocket的实现,用于双向实时通信。文章还提及了将Egret的网络功能移植到CocosCreator的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

CocosCreator版本2.3.4

一、HttpGET

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

cocos客户端:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

//访问地址

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服务端:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

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中

1

console.log(response);   //输出为321

二、HTTPPOST

客户端请求服务器,携带参数name,服务端收到后返回name。

cocos客户端:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

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服务端:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

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输出

1

console.log(response);  //输出123

三、WebSocket

cocos客户端代码:

连接本地服务器127.0.0.1:8001,连接成功后发送一段字符串,并将接收的字符串打印

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

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服务端:

接收字符串成功后,打印接收的数据,并返回一段字符串。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

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中使用,还算方便。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值