一起來學習用nodejs和CocosCreator開發網絡游戲吧(一)--- 搭建


  首先需要安裝開發相關的工具和環境。

  當然,nodejs和CocosCreator,通過搜索引擎很容易就能得到下載鏈接和安裝方法,這里就不浪費筆墨描述了,我們直接開始寫代碼!

  進入到nodejs創建好的工程根目錄下,創建一個index.js的文件,寫入如下代碼:

  

const http = require('http');

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

  通過nodejs,創建了一個監聽本地8181端口的服務端代碼,因為CocosCreator創建的調試頁面,訪問服務器的話會產生跨域問題,所以預先處理了跨域解決方案。

  在終端中運行 :

node index.js

  然后在瀏覽器中輸入地址:http://127.0.0.1:8181

  就能在瀏覽器中看到寫着 hello world! 的頁面,證明服務器已經啟動成功了。

 

  接下來打開CocosCreator,創建一個空白工程,做好項目的目錄結構分類,如下圖所示  

 

  在Script中創建一個network文件夾,並創建一個處理網絡請求的接口,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();
    }
}

 其實這段代碼只處理了一個GET請求方式,沒有更復雜的處理。通過在游戲代碼中引用這個接口,就可以向服務器發送請求了。

 接下來,我們在游戲場景中,添加一張簡單的圖片,一個Label標簽用來顯示后端返回的數據,一個EditBox用來輸入信息發送到服務器,以及一個按鈕來發送數據,如圖所示   

 

 

 

 

 

  然后在Script文件夾下創建游戲腳本HelloWorld.js,並引入相關ui組件和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 () {

    },
});

   將HelloWorld.js附到Canvas組件上,關聯場景中的ui組件,如圖所示:

    

 

 

 

 添加一個按鈕回調函數到HelloWorld.js中,並綁定到SubmitButton上,這樣在場景中點擊按鈕,就會發起一個請求。

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 () {

    },
});

 

 

 

 

  在httpRequest方法中,添加了要訪問的數據對象,包括服務器的url,和發送到服務器的數據,data對象。這里data對象的input屬性數據,來自於輸入框中輸入的內容。

  同時有兩個回調函數,分別是請求成功(success)和請求失敗(fail),請求成功時,將服務器返回的內容展示在ui組件的Label上。請求失敗,在控制台打印失敗信息。

  這樣,前端的基本功能就算完成了。因為向服務器提交了數據,那么就需要在服務端代碼來處理發送的數據,並返回給客戶端,接下來改造一下服務端代碼。

  

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);

  可以看到,通過url組件處理了客戶端發送的請求,獲取到客戶端發來的數據,然后和hello world拼接組合,再返回給客戶端。通過客戶端的success回調函數,可以在客戶端的頁面看到返回信息。

  下面,重新啟動服務端,然后開啟客戶端的調試。會看到如下界面。

  

 

 

 

  這就是客戶端初始化啟動的樣子,接下來在輸入框中輸入一些內容,點擊提交按鈕。

 

 

 

 

 

  可以看到,輸入框中輸入的信息已經提交給服務器,並和hello world拼接后返回給客戶端,並展示在界面中。

  這樣,一個簡單的網絡請求並返回數據的功能就完成了。

 

  至此,搭建服務器和客戶端的工作就告一段落,接下來,讓我們一起來學習如何創建websocket連接,這才是一個真正網游的基石。

 

  文章中的代碼:

  客戶端: https://github.com/MythosMa/CocosCreator_ClientTest.git

  服務端: https://github.com/MythosMa/NodeJS_GameServerTest.git


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM