lua WebSocket服务器

xcode中(苹果电脑)自己在电脑搭建简单的websocket服务器。

1、首先安装node npm

2、使用 npm安装web socket

      npm install nodejs-websocket

3、编写app.js文件 ,在终端 运行。

     node app.js

4、然后在代码中可以做简单的测试。


#ifndef webSocketTest_hpp

#define webSocketTest_hpp

#include <iostream>

using namespace std;

#include "cocos2d.h"

USING_NS_CC;

#include "ui/CocosGUI.h"

using namespace cocos2d::ui;

/*

 WebSocketHTML5开始提供的一种浏览器与服务器间进行全双工通讯的网络技术。在WebSocket API中,浏览器和服务器只需要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。

 */

//#include "extensions/cocos-ext.h"

#include "network/WebSocket.h"

using namespace network;

//cocos2d::network::WebSocket::Delegate定义了使用WebScocket需要监听的回调通知接口。使用WebSocket的类,需要public继承这个Delegate

class WebSocketTest:public Layer,public network::WebSocket::Delegate {

public:

    static Scene* createScene();

    bool init();

    CREATE_FUNC(WebSocketTest);

private:

    //这些虚函数WebSocket的回调

    virtual void onOpen(cocos2d::network::WebSocket* ws);

    virtual void onMessage(cocos2d::network::WebSocket* ws, const WebSocket::Data& data);

    virtual void onClose(WebSocket* ws);

    virtual void onError(WebSocket* ws, const WebSocket::ErrorCode& error);

private:

    //WebSocket实例化

    WebSocket* m_pWebSocket;

};







#include "webSocketTest.hpp"


Scene* WebSocketTest::createScene()

{

    auto scene = Scene::create();

    auto layer = WebSocketTest::create();

    scene->addChild(layer);

    return  scene;

}

bool WebSocketTest::init()

{

    if (!Layer::init()) {

        return false;

    }

    

    auto button1 = cocos2d::ui::Button::create("Open.png");

    button1->setPosition(Vec2(240, 220));

    button1->setScale(0.2);

    this->addChild(button1,2);

    button1->addClickEventListener([=](Ref * sender){

        m_pWebSocket = new WebSocket();

        //init第一个参数是delegate,设置为this,第二个参数是服务器地址。 URL中的"ws://"标识是WebSocket协议,加密的WebSocket"wss://".

//        m_pWebSocket->init(*this, "ws://echo.websocket.org");

        m_pWebSocket->init(*this, "ws://localhost:8001");

    });


    auto button2 = cocos2d::ui::Button::create("Open.png");

    button2->setPosition(Vec2(240, 160));

    button2->setScale(0.2);

    this->addChild(button2,2);

    button2->addClickEventListener([=](Ref * sender){

        if (m_pWebSocket) {

            //init之后,我们就可以调用send接口,往服务器发送数据请求。send有文本和二进制两中模式

            m_pWebSocket->send("Hello WebSocket,I'm a text message!");  //文本

            {

//                char buf[] = "Hello World";

//                m_pWebSocket->send((unsigned char*)buf, sizeof(buf));

            }

        }

    });

    auto button3 = cocos2d::ui::Button::create("Open.png");

    button3->setPosition(Vec2(240, 100));

    button3->setScale(0.2);

    this->addChild(button3,2);

    button3->addClickEventListener([=](Ref * sender){

        if (m_pWebSocket) {

            m_pWebSocket->close();

            m_pWebSocket = nullptr;

        }

    });


    

    

    return true;

}

//init会触发WebSocket链接服务器,如果成功,WebSocket就会调用onOpen,告诉调用者,客户端到服务器的通讯链路已经成功建立,可以收发消息了。

void WebSocketTest::onOpen(cocos2d::network::WebSocket* ws)

{

    if (ws == m_pWebSocket) {

        CCLOG("onOpen!");

    }

}

//network::WebSocket::Data对象存储客户端接收到的数据, isBinary属性用来判断数据是二进制还是文本,len说明数据长度,bytes指向数据

void WebSocketTest::onMessage(cocos2d::network::WebSocket* ws, const WebSocket::Data& data)

{

    if (!data.isBinary) {

        string textStr = string("response text msg :")+data.bytes;

        log(" onMessage: %s",textStr.c_str());

    }

    else

    {

        log(" onMessage: %s",data.bytes);

    }

}

//不管是服务器主动还是被动关闭了WebSocket,客户端将收到这个请求后,需要释放WebSocket内存,并养成良好的习惯:置空指针。

void WebSocketTest::onClose(WebSocket* ws)

{

    if (ws == m_pWebSocket) {

        m_pWebSocket = nullptr;

    }

    CC_SAFE_DELETE(ws);

    CCLOG("onClose!");

}

//客户端发送的请求,如果发生错误,就会收到onError消息,游戏针对不同的错误码,做出相应的处理

void WebSocketTest::onError(WebSocket* ws, const WebSocket::ErrorCode& error)

{

    if (ws == m_pWebSocket) {

        char buf[100] = {0};

        sprintf(buf, "an error was fired. code %d !",error);

        log("onError: %s",buf);

    }

    CCLOG("Error was failed, error code: %d", error);

}




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

猜你喜欢

转载自blog.csdn.net/qq_41939248/article/details/80236374
LUA