[Cocos2d-x]在Cocos2d-x 3.x版本中如何通過WebSocket串連伺服器進行資料轉送

來源:互聯網
上載者:User

[Cocos2d-x]在Cocos2d-x 3.x版本中如何通過WebSocket串連伺服器進行資料轉送
WebSocket

首先建立一個空的檔案夾,通過npm安裝nodejs-websocket

npm install nodejs-websocket

建立app.js檔案:

var ws = require("nodejs-websocket");ws.createServer(function(conn){    conn.on("text", function (str) {        console.log("get the message: "+str);        conn.sendText("the server got the message");    })    conn.on("close", function (code, reason) {        console.log("connection closed");    });    conn.on("error", function (code, reason) {        console.log("an error !");    });}).listen(8001);

通過node app.js啟動,這樣伺服器就搭建好了。

Cocos2d-x
  • 首先在標頭檔中include標頭檔:
#include "network/WebSocket.h"
  • 實現WebSocket的委託:
class HelloWorld : public cocos2d::Layer,public cocos2d::network::WebSocket::Delegate
  • 四個委託中定義的函數介面以及一個用來串連的socketClient對象:
// for virtual function in websocket delegatevirtual void onOpen(cocos2d::network::WebSocket* ws);virtual void onMessage(cocos2d::network::WebSocket* ws, const cocos2d::network::WebSocket::Data& data);virtual void onClose(cocos2d::network::WebSocket* ws);virtual void onError(cocos2d::network::WebSocket* ws, const cocos2d::network::WebSocket::ErrorCode& error);// the websocket io clientcocos2d::network::WebSocket* _wsiClient;
  • 初始化client:
_wsiClient = new cocos2d::network::WebSocket();_wsiClient->init(*this, "ws://localhost:8001");
  • 在cpp檔案中實現這些函數:
// 開始socket串連void HelloWorld::onOpen(cocos2d::network::WebSocket* ws){    CCLOG("OnOpen");}// 接收到了訊息void HelloWorld::onMessage(cocos2d::network::WebSocket* ws, const cocos2d::network::WebSocket::Data& data){        std::string textStr = data.bytes;        textStr.c_str();        CCLOG(textStr.c_str());}// 串連關閉void HelloWorld::onClose(cocos2d::network::WebSocket* ws){    if (ws == _wsiClient)    {        _wsiClient = NULL;    }    CC_SAFE_DELETE(ws);    CCLOG("onClose");}// 遇到錯誤void HelloWorld::onError(cocos2d::network::WebSocket* ws, const cocos2d::network::WebSocket::ErrorCode& error){    if (ws == _wsiClient)    {        char buf[100] = {0};        sprintf(buf, "an error was fired, code: %d", error);    }    CCLOG("Error was fired, error code: %d", error);}

還有一個使用SocketIO的方案,尚未嘗試,明天測試一下:

// Require HTTP module (to start server) and Socket.IOvar http = require('http'), io = require('socket.io');// Start the server at port 8080var server = http.createServer(function(req, res){     // Send HTML headers and message    res.writeHead(200,{ 'Content-Type': 'text/html' });     res.end('<h1>Hello Socket Lover!</h1>');});server.listen(8080);// Create a Socket.IO instance, passing it our servervar socket = io.listen(server);// Add a connect listenersocket.on('connection', function(client){     // Create periodical which ends a message to the client every 5 seconds    var interval = setInterval(function() {        client.send('This is a message from the server!  ' + new Date().getTime());    },5000);    // Success!  Now listen to messages to be received    client.on('message',function(event){         console.log('Received message from client!',event);    });    client.on('disconnect',function(){        clearInterval(interval);        console.log('Server has disconnected');    });});

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.