How to use http and WebSocket in CocosCreator

How to use http and WebSocket in CocosCreator

CocosCreator version 2.3.4

1. HttpGET

Get method, the client requests the local address port 3000 and carries the parameters url and name. After receiving it, the server returns the name parameter.

Cocos client:

//Access address let url = "http://127.0.0.1:3000/?url=123&name=321";
//Create a new Http
let xhr = new XMLHttpRequest();
//Receive data xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
        var response = xhr.responseText;
        console.log(response);
    }
};
//Error handling xhr.onerror = function(evt){
    console.log(evt);
}
//Initialize a request, GET method, true asynchronous request xhr.open("GET", url, true);
//Send request xhr.send();

To facilitate testing, a simple server is built on the local machine using nodejs. After receiving the access, the name value in the request parameter is returned.

Nodejs server:

var app = require('express')(); 
var http = require('http').Server(app);  
 
 
app.get('/', function(req, res){ 
    //Set the domain name allowed to cross domain, * represents allowing any domain name to cross domain res.header("Access-Control-Allow-Origin","*");
    //Allowed header types res.header("Access-Control-Allow-Headers","content-type");
    //Cross-domain allowed request methodres.header("Access-Control-Allow-Methods","DELETE,PUT,POST,GET,OPTIONS");
    res.send(req.query.name); 
}); 
   
http.listen(3000, function(){ 
    console.log('listening on *:3000'); 
});

Run the nodejs server and run the cocos code.

console.log(response); //output is 321

2. HTTP POST

The client requests the server with the parameter name, and the server returns the name after receiving it.

Cocos client:

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 server:

var app = require('express')(); 
var http = require('http').Server(app);  
var querystring = require('querystring');
 
 
app.post('/', function(req, res){ 
    //Set the domain name allowed to cross domain, * represents allowing any domain name to cross domain res.header("Access-Control-Allow-Origin","*");
    //Allowed header types res.header("Access-Control-Allow-Headers","content-type");
    //Cross-domain allowed request methodres.header("Access-Control-Allow-Methods","DELETE,PUT,POST,GET,OPTIONS");
     
    var body = "";
     
    req.on('data', function (chunk) {
        body += chunk; //Be sure to use +=, if body=chunk, because favicon.ico is requested, body will be equal to {}
        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 output

console.log(response); //output 123

WebSocket

Cocos client code:

Connect to the local server 127.0.0.1:8001, send a string after the connection is successful, and print the received string

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 sending message.");
        ws.send("Hello WebSocket, I'm a text message.");
    }
    else {
        console.log("WebSocket instance wasn't ready...");
    }
}, 3000);

Nodejs server:

After successfully receiving the string, print the received data and return a string.

var ws = require("nodejs-websocket");
  
console.log("Start creating websocket");
var server = ws.createServer(function(conn){
    console.log("Connection successful");
    conn.on("text", function (obj) {
       console.log("Receive:",obj);
        conn.send("message come from server");     
          
    })
    conn.on("close", function (code, reason) {
        console.log("Close connection")
    });
    conn.on("error", function (code, reason) {
        console.log("Abnormal closure")
    });
}).listen(8001)
console.log("Start creating websocket");

Test results, client browser output:

Output on the nodejs side:

4. Transplant Egret's http and websocket to cocos

Because cocos does not have encapsulation tool classes, it is quite convenient to directly transplant http and websocket from Egret to cocos for use.

The above is the detailed content of Http and WebSocket of Cocos Creator. For more information about Cocos Creator, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Unity3D realizes camera lens movement and limits the angle
  • Detailed explanation of how to use several timers in CocosCreator
  • CocosCreator learning modular script
  • How to use physics engine joints in CocosCreator
  • How to use JSZip compression in CocosCreator
  • CocosCreator Getting Started Tutorial: Making Your First Game with TS
  • Interpretation of CocosCreator source code: engine startup and main loop
  • CocosCreator general framework design resource management
  • How to make a List in CocosCreator
  • Analysis of CocosCreator's new resource management system
  • How to use cc.follow for camera tracking in CocosCreator

<<:  Detailed explanation of MySQL precompilation function

>>:  How to view Docker container application logs

Recommend

WeChat applet implements search box function

This article example shares the specific code for...

Centos8 builds nfs based on kdc encryption

Table of contents Configuration nfs server (nfs.s...

Solution to using html2canvas to process Dom elements with Baidu map into images

Problem 1: Baidu Map uses tiled images (the map i...

JavaScript plugin encapsulation for table switching

This article shares the encapsulation code of Jav...

A brief analysis of Linux resolv.conf

1. Introduction resolv.conf is the configuration ...

A brief discussion on the lazy loading attribute pattern in JavaScript

Table of contents 1. Introduction 2. On-demand at...

Summary of commonly used operators and functions in MySQL

Let’s build the data table first. use test; creat...

Analysis of pitfalls in rounding operation of ROUND function in MySQL

This article uses examples to illustrate the pitf...

How to use IDEA to configure tomcat and create JSP files

Before using idea to write JSP files, you need to...

Nginx+FastDFS to build an image server

Installation Environment Centos Environment Depen...

How to backup MySQL regularly and upload it to Qiniu

In most application scenarios, we need to back up...

Brief analysis of MySQL union and union all

In the database, both UNION and UNION ALL keyword...

Windows 10 + mysql 8.0.11 zip installation tutorial detailed

Prepare: MySQL 8.0 Windows zip package download a...

How does Vue solve the cross-domain problem of axios request front end

Table of contents Preface 1. Why do cross-domain ...

Detailed explanation of MySQL combined query

Using UNION Most SQL queries consist of a single ...