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

Implementation of Vue counter

Table of contents 1. Implementation of counter 2....

Navicat connects to MySQL8.0.11 and an error 2059 occurs

mistake The following error occurs when connectin...

Detailed explanation of the pitfalls of mixing npm and cnpm

Table of contents cause reason Introduction to NP...

W3C Tutorial (13): W3C WSDL Activities

Web Services are concerned with application-to-ap...

Detailed explanation of keywords and reserved words in MySQL 5.7

Preface The keywords of MySQL and Oracle are not ...

A brief discussion on whether CSS animation will be blocked by JS

The animation part of CSS will be blocked by JS, ...

HTML symbol to entity algorithm challenge

challenge: Converts the characters &, <, &...

How to use Docker containers to implement proxy forwarding and data backup

Preface When we deploy applications to servers as...

How to configure anti-hotlinking for nginx website service (recommended)

1. Principle of Hotlinking 1.1 Web page preparati...

Implementation of Docker deployment of Nuxt.js project

Docker official documentation: https://docs.docke...

CSS to achieve dynamic secondary menu

Dynamically implement a simple secondary menu Whe...

Docker installs redis 5.0.7 and mounts external configuration and data issues

Redis is an open source NoSQL database written in...

Introduction to Semantic XHTML Tags

The first point to make is that people can judge t...

Vue implements zip file download

This article example shares the specific code of ...