zoukankan      html  css  js  c++  java
  • [Cocos2d-x]在Cocos2d-x 3.x如何通过版本号WebSocket连接server数据的传输

    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 delegate
    virtual 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 client
    cocos2d::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.IO
    var http = require('http'), io = require('socket.io');
    
    // Start the server at port 8080
    var 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 server
    var socket = io.listen(server);
    
    // Add a connect listener
    socket.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');
        });
    
    });

    版权声明:本文博客原创文章,博客,未经同意,不得转载。

  • 相关阅读:
    windows代码,传入文件名,遍历此目录下所有文件.
    windows,分割路径.得出目录
    windows代码,路径分割
    windows下,读取快捷方式lnk所指向的路径
    【Unity】3.2 利用预设(Prefab)制作可复用的组件
    【Unity】3.1 利用内置的3D对象创建三维模型
    【Unity】3.0 第3章 创建和导入3D模型
    【Unity】2.11 了解游戏有哪些分类对你开阔思路有好处
    【Unity】2.10 利用VS2015编辑Unity的C#脚本
    【Unity】2.9 光源(Lights)
  • 原文地址:https://www.cnblogs.com/bhlsheji/p/4625945.html
Copyright © 2011-2022 走看看