Nodejs together to learn with online games and CocosCreator bar (a) --- build

  First you need to install related to the development tools and environment.

  Of course, nodejs and CocosCreator, search engines can easily get the download link and installation method described here is not a waste of ink, we just start writing code!

  Proceed to the next nodejs create a good project root directory, create a index.js file, write the following code:

  

const http = require('http');

http.createServer(function(req, res){
    res.setHeader("Access-Control-Allow-Origin", "*");//跨域
    res.write("hello world!");
    res.end();
}).listen(8181);

  By nodejs, created local service-side code 8181 port of a listener, because debugging page CocosCreator created, will have access to the server, then cross-domain problem, so pre-treated cross-domain solutions.

  Running in the terminal:

node index.js

  Then enter the address in your browser: http: //127.0.0.1: 8181

  You can see the page that says hello world! In the browser, the server has been launched prove successful.

 

  Next, open CocosCreator, create a blank project, do a good job classification project directory structure, as shown below  

 

  Script created in a network folder, and you create an interface processing network requests, httpServer.js

  

export default {
    request: (obj) => {
        let httpRequest = new XMLHttpRequest();
        let time = 5 * 1000;
        let timeout = false;

        //超时
        let timer = setTimeout(() => {
            timeout = true;
            httpRequest.abort();
        }, time);

        let url = obj.url;

        //请求参数
        if(typeof obj.data === 'object') {
            let kvs = [];
            for(let k in obj.data) {
                kvs.push(encodeURIComponent(k) + '=' + encodeURIComponent(obj.data[k]));
            }
            url += '?';
            url += kvs.join('&');
        }

        httpRequest.open(obj.method ? obj.method : 'GET', url ,true);

        httpRequest.onreadystatechange = () => {
            let response = httpRequest.responseText;
            clearTimeout(timer);

            if(httpRequest.readyState === 4) {
                if(typeof obj.success === 'function') {
                    let resJson = JSON.parse(response);
                    obj.success(resJson);
                }
            }else {
                if(typeof obj.fail === 'function') {
                    obj.fail(response);
                }
            }
        };

        httpRequest.send();
    }
}

 In fact, this code only deals with the way a GET request, no more complex processing. Game by reference in this interface code, the request can be sent to the server.

 Next, we game scene, add a simple picture, data for displaying a Label Label returned by the backend, a EditBox to input transmission information to the server, and a button to transmit the data, shown in FIG.   

 

 

 

 

 

  Then create script HelloWorld.js game in Script folder, and the introduction of relevant ui components and httpServer.

 

import http from './network/httpServer';

cc.Class({
    extends: cc.Component,

    properties: {
        subButton: {
            default: null,
            type: cc.Button
        },

        tipLabel: {
            default: null,
            type: cc.Label
        },

        input: {
            default: null,
            type: cc.EditBox
        }
    },

    onLoad() {

    },

    start () {

    },
});

   The Canvas HelloWorld.js attached to the assembly, the associated scene components ui, as shown:

    

 

 

 

 Add a button callback function to HelloWorld.js in and bound to the SubmitButton, so click on the button at the scene, it will initiate a request.

import http from './network/httpServer';

cc.Class({
    extends: cc.Component,

    properties: {
        subButton: {
            default: null,
            type: cc.Button
        },

        tipLabel: {
            default: null,
            type: cc.Label
        },

        input: {
            default: null,
            type: cc.EditBox
        }
    },

    onLoad() {

    },

    //发送请求的方法
    httpRequest() {
        let obj = {
            url : 'http://127.0.0.1:8181',
            data:{
                input: this.input.string
            },
            success : (res) => {
                this.tipLabel.string = res.info;
            },
            fail: (res) => {
                console.log("fail!");
                console.log(res);
            }
        }
        http.request(obj);
    },


    start () {

    },
});

 

 

 

 

  In httpRequest method, add a data object to be accessed, including data url server, and sent to the server, data objects. Here attribute data input of the data object, the content input from the input box.

  While two callback functions, which are successful request (Success) and request failure (Fail), when the request is successful, the server returns the content displayed on the Label ui assembly. The request failed print failure in the console.

  In this way, the basic functions of the front end is complete. Because the submitted data to the server, you need the server-side code to handle data sent and returned to the client, then transform what server-side code.

  

const http = require('http');
const url = require('url');


http.createServer(function(req, res){
    var request = url.parse(req.url, true).query
    var response = {
        info: request.input ? request.input + ', hello world' : 'hello world'
    };
    res.setHeader("Access-Control-Allow-Origin", "*");//跨域
    res.write(JSON.stringify(response));
    res.end();
}).listen(8181);

  It can be seen by the processing component url request sent by the client, the client obtains the data sent, and then stitching composition hello world, then returned to the client. By success callback client, you can see the return information on the client's page.

  Next, restart the server, and then turn on debugging client. You will see the following interface.

  

 

 

 

  This is the way the client initial start, then type something in the input box, click on the submit button.

 

 

 

 

 

  You can see, the information entered in the input box has been submitted to the server, and after stitching and hello world back to the client and shows in the interface.

  In this way, a simple request and returns the data network function is completed.

 

  At this point, set up the server and client work came to an end, then, let us work together to learn how to create websocket connection, this is the cornerstone of a real online games.

 

  Article code:

  Client: https://github.com/MythosMa/CocosCreator_ClientTest.git

  Server: https://github.com/MythosMa/NodeJS_GameServerTest.git

Guess you like

Origin www.cnblogs.com/mythosma/p/11898695.html
Recommended